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

房东的猫 提交于 2019-11-29 09:35:07

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<AfterIfDirective> = new EventEmitter();

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

Sample HTML:

<div *ngIf="user$ | async as user" class="container" (after-if)="your expression">
    <p>user.name</p>
</div>

A solution without the creation of a new directive is to take advange of @ViewChild behaviour:

Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

The important part is If the view DOM changes wich means that in this case this'll only be triggered when the element is created or destroyed.

First declare a variable name for the element, for the sample i used #userContent

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

Then add a @ViewChild reference inside your component:

    @ViewChild('userContent') set userContent(element) {
      if (element) {
         // here you get access only when element is rendered (or destroyed)
      }
    }

This solution was provided inside another question, also @ViewChild behaviour detail is available here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!