简体   繁体   English

动态ViewChildren组件的Angular 2使用方法

[英]Angular 2 use method of dynamic ViewChildren component

I have many instances of child component that creates via *ngFor. 我有许多通过* ngFor创建的子组件实例。 I want to use some method of selected one (I select one from parent). 我想使用某种方法选择一个(我从父母中选择一个)。 How I can do this? 我该怎么做?

Because ViewChild is not works (I have many components). 因为ViewChild不起作用(我有很多组件)。 Also ViewChildren also not working. 另外ViewChildren也无法正常工作。 Because I created it dynamically after some delay and ViewChildren have 0 length. 因为我是在延迟后动态创建的,并且ViewChildren的长度为0。

Thanks for any information. 感谢您提供任何信息。

just for example. 仅举例来说。 _schedCompntnsArr have 0 length (but on page I have 4 componnets). _schedCompntnsArr的长度为0(但在页面上我有4个componnet)。

 directives: [
    SchedulerComponent
  ],

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

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

Tested the following code with RC 4 and it worked as expected: 使用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