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

Issue

If I have the following:

<div *ngIf="user$ | async as user" class="container">
   <p>{{user.name}}</p>
</div>

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

Solution

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 {
    @Output('after-if')
    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">
   <p>{{user.name}}</p>
</div>

Leave a Reply

(*) Required, Your email will not be published