As the code provided bellow. I tried to select a dynamic element generated by ngIf but failed.
I used two ways in total.
You can't get the element when the *ngIf="expr"
expression is false because then the element doesn't exist.
The value is not yet set in ngOnInit()
, only when ngAfterViewInit()
is called.
Plunker example
@Component({
selector: 'my-app',
template: `
`
,
})
export class App {
@ViewChild('button') button: ElementRef;
prop:boolean = true;
ngAfterViewInit() {
console.log(this.button);
}
}
Plunker example with ViewChildren
@Component({
selector: 'my-app',
template: `
`
,
})
export class App {
@ViewChildren('button') button: QueryList;
prop:boolean = true;
ngAfterViewInit() {
console.log(this.button.toArray());
this.button.changes.subscribe(val => {
console.log(this.button.toArray());
});
}
}