Angular 2使用动态ViewChildren组件

时间:2016-07-08 14:28:59

标签: typescript angular

我有许多通过* ngFor创建的子组件实例。我想使用一些选择的方法(我从父母中选择一个)。我怎么能这样做?

因为ViewChild不起作用(我有很多组件)。 ViewChildren也无法正常工作。因为我在延迟一段时间后动态创建了它,而ViewChildren的长度为0。

感谢您提供任何信息。

仅举例。 _schedCompntnsArr的长度为0(但在页面上我有4个组件)。

 directives: [
    SchedulerComponent
  ],

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

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

1 个答案:

答案 0 :(得分:1)

使用R.C 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
  }