相关疑难解决方法(0)

如何选择*ngIf渲染的动态元素

正如下面提供的代码.我试图选择由ngIf生成的动态元素但是失败了.

我总共用了两种方法.

  1. ElementRef和querySelector

组件模板:

    `<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.

  1. @ViewChild

组件模板:

    `<div class="test" *ngIf="expr">
      <a #button>Value 1</a>
    </div>
    <div class="test" *ngIf="!expr"> …
Run Code Online (Sandbox Code Playgroud)

javascript angular

6
推荐指数
2
解决办法
3214
查看次数

标签 统计

angular ×1

javascript ×1