How can I select dynamic elements rendered by *ngIf

前端 未结 4 403
孤城傲影
孤城傲影 2021-01-18 01:48

As the code provided bellow. I tried to select a dynamic element generated by ngIf but failed.

I used two ways in total.

  1. ElementRef and querySelector
4条回答
  •  抹茶落季
    2021-01-18 01:59

    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());
        });
    
      }
    }
    

提交回复
热议问题