[Fixed] Event to fire when an angular *ngIf statement evaluates in template


If I have the following:

<div *ngIf="user$ | async as user" class="container">

Is there a way I can execute code when the div above finally appears on screen?


The *ngIf will remove that DOM element and all attached components/directives. So you can just write a simple directive that executes an event when it’s first created. When the *ngIf transitions from false to true the directive will be created (again, and again, etc…)

@Directive({selector: '[after-if]'})
export class AfterIfDirective implements AfterContentInit {
    public after: EventEmitter<void> = new EventEmitter<void>();

    public ngAfterContentInit(): void {
       // timeout helps prevent unexpected change errors
       setTimeout(()=> this.after.next());

Sample HTML:

<div *ngIf="user$ | async as user" (after-if)="your expression">

Leave a Reply

(*) Required, Your email will not be published