Like the code below. I tried to select the dynamic element generated by ngIf, but could not.
I used two methods in total.
- ElementRef and querySelector
component template:
`<div class="test" *ngIf="expr"> <a id="button">Value 1</a> </div> <div class="test" *ngIf="!expr"> <a id="button">Value 2</a> </div>`
component class:
expr: boolean; constructor( private elementRef: ElementRef, ) { } ngOnInit(): void{ //Call Ajax and set the value of this.expr based on the callback; //if expr == true, then show text Value 1; //if expr == false, then show text Value 2; } ngAfterViewInit(): void{ console.log(this.elementRef.nativeElement.querySelector('#button')); }
The result of the output is null .
- @ViewChild
component template:
`<div class="test" *ngIf="expr"> <a #button>Value 1</a> </div> <div class="test" *ngIf="!expr"> <a #button>Value 2</a> </div>`
component class:
@ViewChild('button') button: elementRef; expr: boolean; ngOnInit(): void{ //Call Ajax and set the value of this.expr based on the callback; //if expr == true, then show text Value 1; //if expr == false, then show text Value 2; } ngAfterViewInit(): void{ console.log(this.button); }
Output Result: undefined ;
Is there a way to get the dynamic dom generated by * ngIf?
Finally, the problem is resolved using @ViewChildren.
And to register an updated result, you must use a separate function.
For instance:
Incorrect code:
@ViewChildren('button') buttons: ElementRef; function(): void{ this.expr = true;
Right code:
@ViewChildren('button') buttons: ElementRef; function(): void{ this.expr = true;
source share