How can I select dynamic elements rendered by *ngIf

前端 未结 4 450
孤城傲影
孤城傲影 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:52

    If you need the element only in the moment that someone interacts with it (e.g. clicks on it) or with a sibling or child element of it you can pass it's reference with the event.

    Template:

    
    

    Code:

    onButton1(button: HTMLButtonElement) {
    }
    

    If you need the element without interaction with it you might also look at the ViewChildren query instead of ViewChild.

    You can set it up with

    @ViewChildren('button') buttons: QueryList;    
    

    You can then subscribe to changes of elements that match a selector through this.buttons.changes.subscribe(...). If the element get's created or deleted you will get notified through the subscription. However my first way involves far less boilerplate code.

    Alternativly you can also only access the QueryList synchronously in moments where you are sure that the element exists (through some preconditions). In your example you should be able to retrieve the button with

    let button: ElementRef = this.buttons.first;
    

    in these cases.

提交回复
热议问题