正如下面提供的代码.我试图选择由ngIf生成的动态元素但是失败了.
我总共用了两种方法.
组件模板:
`<div class="test" *ngIf="expr">
<a id="button">Value 1</a>
</div>
<div class="test" *ngIf="!expr">
<a id="button">Value 2</a>
</div>`
Run Code Online (Sandbox Code Playgroud)
组件类:
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'));
}
Run Code Online (Sandbox Code Playgroud)
输出结果是null.
组件模板:
`<div class="test" *ngIf="expr">
<a #button>Value 1</a>
</div>
<div class="test" *ngIf="!expr"> …Run Code Online (Sandbox Code Playgroud)