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

Sammy picture Sammy · Jun 10, 2017 · Viewed 11k times · Source

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?

Answer

Reactgular picture Reactgular · Jun 24, 2017

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>