【问题标题】:event when div ngIf is rendered渲染 div ngIf 时的事件
【发布时间】:2018-05-08 20:22:54
【问题描述】:

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

我有一个带有 ngIf 条件的 div,我想在 div 被渲染时捕获一个事件。假设您可以使用AfterContentInit 事件。 我上面引用的文章显示了一个示例,我已经复制了该示例,但没有成功。

我不知道我做错了什么,但我无法让它工作。我没有收到任何错误,但它对我不起作用。

我的指令定义为:

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

在我的页面组件中我导入。

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 中不起作用吗?

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

【问题讨论】:

  • 你能用 Clicked 函数发布你的代码吗?还可以在setTimeout 中输入控制台日志,看看它是否在那里触发。
  • 这里是 Clicked 函数。 Clicked() { console.log('某事被点击'); }
  • 为什么选择器名称和输入名称这么奇怪? afterIf 的默认 Angular 样式有什么问题?

标签: angular event-handling


【解决方案1】:

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

模板:

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

组件:

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

【讨论】:

  • 谢谢你!你是我今天的英雄。
猜你喜欢
  • 2018-09-19
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 2019-03-06
  • 1970-01-01
  • 2015-07-02
相关资源
最近更新 更多