【问题标题】:Angular2 *ngIf with child directiveAngular2 *ngIf 与子指令
【发布时间】:2017-03-03 09:44:26
【问题描述】:

我似乎无法让我的指令起作用,我想知道这是否是由于使用了 *ngif。

组件 HTML:

<div *ngIf="ticket" class="row">
   <div class="col-xs-12">
      <h4 appUsername>{{ticket.raisedBy.firstName}} {{ticket.raisedBy.surname}}</h4>
   </div>
</div>

指令

 import { Directive, ElementRef, Input } from '@angular/core';

 @Directive({
  selector: '[appUsername]'
 })

 export class UsernameDirective {constructor(el: ElementRef) {
    console.log('App Username directive init');
    el.nativeElement.style.color = 'red';
 }
}

当我从 ngOnInit 上的 JSON 服务收集数据时,组件 HTML 中需要 *ngIf。

为简洁而忽略代码:我将指令添加到导出指令的“共享”模块中。然后将该模块导入到主应用程序模块中。

这是一个已知问题还是我的代码?

更新我现在可以正常工作了,但是我必须将指令导入到包含该组件的模块中。我可以不将它导入到 AppModule 中然后全局使用吗?

【问题讨论】:

  • 什么不起作用?预期的行为是什么?您是否尝试将您的 red 代码移动到 ngAfterViewInit()?
  • @GünterZöchbauer 该指令不会更改组件 HTML 中 h4 中文本的颜色。也不触发 console.log
  • 您是否将共享模块导入到包含上述组件的模块中?
  • @GünterZöchbauer 导入一切正常,应用程序控制台中没有编码错误。
  • 如果构造函数没有被执行,它几乎 100% 是模块配置的问题。选择器匹配,没有太多其他可能导致它。

标签: angular directive angular-ng-if


【解决方案1】:

Angular 模块系统是这样工作的:

  • 您需要 declare 和 Component/Directive/... 恰好是一个 NgModule。
    然后,您可以在属于此NgModule 的Components 中使用它。
  • 要在任何其他NgModule 中使用Component/Directive/...,您需要将export 从NgModule 和import 中声明NgModule 中@ 987654335@你想用的地方。

在您的情况下,您在 SharedModule 和 import 中使用 declare 和 export Directive AppModule 中的 SharedModule,但您在另一个 NgModule 中使用 Directive,不知道importSharedModule,也不知道importAppModule,因此不知道你的Directive。

所以要在NgModule 中使用某些东西,它需要declare 它,import 声明NgModule 或import 一个NgModule,其中imports 声明NgModule。 仅当声明 NgModule 导出 Directive 时,导入才有效。

【讨论】:

    猜你喜欢
    • 2017-12-16
    • 2016-07-14
    • 2017-02-08
    • 2017-06-06
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2020-07-15
    • 2017-08-26
    相关资源
    最近更新 更多