我正在学习Angular 2。

我想使用@ViewChild Annotation从父组件访问子组件。

下面是一些代码行:

在BodyContent。我有:

import { ViewChild, Component, Injectable } from 'angular2/core';
import { FilterTiles } from '../Components/FilterTiles/FilterTiles';

@Component({
    selector: 'ico-body-content',
    templateUrl: 'App/Pages/Filters/BodyContent/BodyContent.html',
    directives: [FilterTiles] 
})
export class BodyContent {
    @ViewChild(FilterTiles) ft: FilterTiles;

    public onClickSidebar(clickedElement: string) {
        console.log(this.ft);
        var startingFilter = {
            title: 'cognomi',
            values: [ 'griffin', 'simpson' ]
        }
        this.ft.tiles.push(startingFilter);
    } 
}

FilterTiles.ts:

 import { Component } from 'angular2/core';

 @Component({
     selector: 'ico-filter-tiles',
     templateUrl: 'App/Pages/Filters/Components/FilterTiles/FilterTiles.html'
 })
 export class FilterTiles {
     public tiles = [];

     public constructor(){};
 }

最后是模板(在评论中建议):

BodyContent.html

<div (click)="onClickSidebar()" class="row" style="height:200px; background-color:red;">
    <ico-filter-tiles></ico-filter-tiles>
</div>

FilterTiles.html

<h1>Tiles loaded</h1>
<div *ngFor="#tile of tiles" class="col-md-4">
     ... stuff ...
</div>

FilterTiles.html模板被正确加载到ico-filter-tiles标签(确实我能够看到标题)。

注意:BodyContent类使用DynamicComponetLoader: dcl注入到另一个模板(Body)中。loadAsRoot(BodyContent, '#ico-bodyContent',注入器):

import { ViewChild, Component, DynamicComponentLoader, Injector } from 'angular2/core';
import { Body } from '../../Layout/Dashboard/Body/Body';
import { BodyContent } from './BodyContent/BodyContent';

@Component({
    selector: 'filters',
    templateUrl: 'App/Pages/Filters/Filters.html',
    directives: [Body, Sidebar, Navbar]
})
export class Filters {

    constructor(dcl: DynamicComponentLoader, injector: Injector) {
       dcl.loadAsRoot(BodyContent, '#ico-bodyContent', injector);
       dcl.loadAsRoot(SidebarContent, '#ico-sidebarContent', injector);
   } 
}

问题是,当我试图将ft写入控制台日志时,我得到了未定义,当然,当我试图在“tiles”数组内推一些东西时,我会得到一个异常:“没有属性瓷砖”。

还有一件事:FilterTiles组件似乎正确加载,因为我能够看到它的html模板。

有什么建议吗?


当前回答

我借助更改检测以及视图容器引用的延迟初始化解决了这个问题。

HTML设置:

<ng-container *ngIf="renderMode === 'modal'" [ngTemplateOutlet]="renderModal">
</ng-container>
<ng-container *ngIf="renderMode === 'alert'" [ngTemplateOutlet]="renderAlert">
</ng-container>

<ng-template #renderModal>
  <div class="modal">
    <ng-container appSelector></ng-container>
  </div>
</ng-template>

<ng-template #renderAlert>
  <div class="alert">
    <ng-container appSelector></ng-container>
  </div>
</ng-template>

组件:

@ViewChild(SelectorDirective, { static: true }) containerSelector!: SelectorDirective;

constructor(private cdr: ChangeDetectorRef) { }

ngOnInit(): void {
  // step: 1
  this.renderMode = someService.someMethod();
  // step: 2
  this.cdr.markForCheck();
  // step: 3
  const viewContainerRef = this.containerSelector?.viewContainerRef;
  if (viewContainerRef) {
    // logic...
  }
}

修改代码,使HTML所依赖的条件(*ngIf)首先更新 一旦条件更新,手动触发ChangeDetection 在手动cdr触发后从ViewChild中获取引用,并继续进行逻辑操作。

其他回答

对我来说,问题是我引用了元素上的ID。

@ViewChild('survey-form') slides:IonSlides;

<div id="survey-form"></div>

而不是这样:

@ViewChild('surveyForm') slides:IonSlides;

<div #surveyForm></div>

这对我来说是可行的,参见下面的示例。

import {Component, ViewChild, ElementRef} from 'angular2/core'; @Component({ selector: 'app', template: ` <a (click)="toggle($event)">Toggle</a> <div *ngIf="visible"> <input #control name="value" [(ngModel)]="value" type="text" /> </div> `, }) export class AppComponent { private elementRef: ElementRef; @ViewChild('control') set controlElRef(elementRef: ElementRef) { this.elementRef = elementRef; } visible:boolean; toggle($event: Event) { this.visible = !this.visible; if(this.visible) { setTimeout(() => { this.elementRef.nativeElement.focus(); }); } } }

我借助更改检测以及视图容器引用的延迟初始化解决了这个问题。

HTML设置:

<ng-container *ngIf="renderMode === 'modal'" [ngTemplateOutlet]="renderModal">
</ng-container>
<ng-container *ngIf="renderMode === 'alert'" [ngTemplateOutlet]="renderAlert">
</ng-container>

<ng-template #renderModal>
  <div class="modal">
    <ng-container appSelector></ng-container>
  </div>
</ng-template>

<ng-template #renderAlert>
  <div class="alert">
    <ng-container appSelector></ng-container>
  </div>
</ng-template>

组件:

@ViewChild(SelectorDirective, { static: true }) containerSelector!: SelectorDirective;

constructor(private cdr: ChangeDetectorRef) { }

ngOnInit(): void {
  // step: 1
  this.renderMode = someService.someMethod();
  // step: 2
  this.cdr.markForCheck();
  // step: 3
  const viewContainerRef = this.containerSelector?.viewContainerRef;
  if (viewContainerRef) {
    // logic...
  }
}

修改代码,使HTML所依赖的条件(*ngIf)首先更新 一旦条件更新,手动触发ChangeDetection 在手动cdr触发后从ViewChild中获取引用,并继续进行逻辑操作。

角: 在HTML中更改*ngIf的显示样式为'block'或'none'。

selector: 'app',
template:  `
    <controls [style.display]="controlsOn ? 'block' : 'none'"></controls>
    <slideshow (mousemove)="onMouseMove()"></slideshow>
`,
directives: [SlideshowComponent, ControlsComponent]

我的解决方法是使用[style.display]="getControlsOnStyleDisplay()"而不是*ngIf="controlsOn"。块在那里,但没有显示出来。

@Component({
selector: 'app',
template:  `
    <controls [style.display]="getControlsOnStyleDisplay()"></controls>
...

export class AppComponent {
  @ViewChild(ControlsComponent) controls:ControlsComponent;

  controlsOn:boolean = false;

  getControlsOnStyleDisplay() {
    if(this.controlsOn) {
      return "block";
    } else {
      return "none";
    }
  }
....