Velidan
Velidan

Reputation: 6004

Angular 2 use method of dynamic ViewChildren component

I have many instances of child component that creates via *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). Also ViewChildren also not working. Because I created it dynamically after some delay and ViewChildren have 0 length.

Thanks for any information.

just for example. _schedCompntnsArr have 0 length (but on page I have 4 componnets).

 directives: [
    SchedulerComponent
  ],

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

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

Upvotes: 0

Views: 1311

Answers (1)

knikolov
knikolov

Reputation: 1800

Tested the following code with R.C 4 and it worked as expected:

@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
  }

Upvotes: 1

Related Questions