簡體   English   中英

動態ViewChildren組件的Angular 2使用方法

[英]Angular 2 use method of dynamic ViewChildren component

我有許多通過* ngFor創建的子組件實例。 我想使用某種方法選擇一個(我從父母中選擇一個)。 我該怎么做?

因為ViewChild不起作用(我有很多組件)。 另外ViewChildren也無法正常工作。 因為我是在延遲后動態創建的,並且ViewChildren的長度為0。

感謝您提供任何信息。

僅舉例來說。 _schedCompntnsArr的長度為0(但在頁面上我有4個componnet)。

 directives: [
    SchedulerComponent
  ],

@ViewChildren(SchedulerComponent) schedCompntsList: QueryList<SchedulerComponent>;

ngAfterViewInit() {
  this._schedCompntnsArr = this.schedCompntsList.toArray();
}

使用RC 4測試了以下代碼,並且按預期方式工作:

@Component({
 selector: 'my-app',
 template: `
   <FooComponent *ngFor="let item of items let i=index" [selected]="i == selected">
        {{item.city}} - {{item.temp}}
   </FooComponent>
`,
directives: [FooComponent]
})
class AppComponent {
  public selected: number = 1;

  public items: any = [{
        disabled: true,
        city: "Paris",
        temp: 17
  }, {
        disabled: false,
        city: "New York",
        temp: 29
  }, {
        disabled: false,
        city: "Helsinki",
        temp: 23
  }]

  foo: any;

  @ViewChildren(FooComponent) children:QueryList<FooComponent>;

  ngAfterViewInit() {
        this.foo = this.children.toArray();
        console.log(this.foo.length); //logs 3
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM