在模板中评估有角* ngIf语句时将触发的事件 [英] Event to fire when an angular *ngIf statement evaluates in template

查看:157
本文介绍了在模板中评估有角* ngIf语句时将触发的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有以下条件:

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

当上面的div最终出现在屏幕上时,是否可以执行代码?

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

推荐答案

*ngIf将删除该DOM元素和所有附加的组件/指令.因此,您只需编写一个简单的指令即可在事件首次创建时执行该事件.当*ngIf false 转换为 true 时,将创建指令(再次,等等,等等)

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());
    }
}

示例HTML:

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

这篇关于在模板中评估有角* ngIf语句时将触发的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆