div ngIf呈现时的事件 [英] event when div ngIf is rendered

查看:262
本文介绍了div ngIf呈现时的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以下位置查看问题: https://stackoverflow.com/a/44737636/973651

I was looking at issue at: https://stackoverflow.com/a/44737636/973651

我有一个条件为ngIf的div,我想捕获div呈现时的事件.可以使用AfterContentInit事件. 我在上面引用的文章显示了一个示例,我已经复制了一个示例,但是使其无法正常工作.

I've a div with an ngIf condition, and I'd like to capture an event for when the div gets rendered. Supposedly, you can use the AfterContentInit event. The article I cited above, shows an example, which I've replicated but no luck in getting it to work.

我不知道我在做什么错,但是我无法使它正常工作.我没有收到任何错误,但是对我来说不起作用.

I don't know what I'm doing wrong, but I can't get this to work. I get no errors, but it doesn't work for me.

我的指令定义为:

import { AfterContentInit, EventEmitter, Output, Directive } from '@angular/core';

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

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

在我的页面组件中导入.

In my page component I import.

import { AfterIfDirective } from '../directives/after-if';


@NgModule({
  providers: [],
  imports: [NgModel, BrowserAnimationsModule, HttpClientModule, 
      AfterIfDirective],
  exports: [NgModel, BrowserAnimationsModule, AfterIfDirective]
})

和html中的

<div *ngIf="chkTearline.checked; else NotTearline" (after-if)="Clicked()" >

我想念什么?

这在Angular 5中不起作用吗?

Does this not work in Angular 5?

  Clicked() {
    console.log('something got clicked');
  }

推荐答案

您可以使用setter,如下例所示:

You can use setter like in example below:

模板:

...
<div #elementToCheck *ngIf="expr"></div>
...

组件:

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

这篇关于div ngIf呈现时的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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