3

In Angular2 , I want to find my children components , that was declared in the template in run time. how can I do it? For Example:

@Component({

template: `
<cmp1 *ngIf=expression></cmp1>
<cmp2 *ngIf=!expression></cmp2>
    `

})
export class Component3{

findChild(){
// How to find cmp2
}

}
almog
  • 798
  • 1
  • 7
  • 18

1 Answers1

1

Not sure what you mean with "at runtime" but this is how it's usually done:

@Component({
template: `
<cmp1 #cmp *ngIf=expression></cmp1>
<cmp2 #cmp *ngIf=!expression></cmp2>
`
})
export class Component3{

  @ViewChildren('cmp') cmp:QueryList;

  findChild(){
    return this.cmp.toArray()[0];
  }
}

Component1 needs to be imported.

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • note that the ngIf , the ngIf will show only one of the two component. Lets say that the expression = true. cmp1 will be rendered , cmp2 wont be... When I will change the expression to false at runtime, cmp1 will be removed from the DOM and cmp2 should be rendered. In this scenario how will I get cmp2? – almog Jul 28 '16 at 10:05
  • Now I see what you mean. I updated my answer. A better way might be to use `@ViewChild()` as demonstrated before and move `expression` to a method and check this method in `findChild` like `if(expression) { return cmp1; } else { return cmp2;}` – Günter Zöchbauer Jul 28 '16 at 10:11