Angular2 *ngIf 与子指令
Angular2 *ngIf with child directive
我似乎无法让我的指令起作用,想知道这是否是由于使用了 *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';
}
}
组件 HTML 中需要 *ngIf,因为我正在 ngOnInit 上从 JSON 服务收集数据。
为简洁起见忽略了代码:我正在将指令添加到导出指令的 "shared" 模块中。然后将此模块导入到主应用程序模块中。
这是已知问题还是我的代码?
更新 我现在可以正常工作了,但是我必须将指令导入到包含该组件的模块中。我可以不将它导入 AppModule 然后全局使用吗?
Angular
模块系统是这样工作的:
- 您需要
declare
一个 Component
/Directive
/... 在一个 NgModule
.
中
然后您可以在属于此 NgModule
的 Component
中使用它。
- 要在任何其他
NgModule
中使用 Component
/Directive
/...,您需要 export
它来自声明 NgModule
和 import
在 NgModule
中要使用它的地方声明 NgModule
。
在你的情况下你 declare
和 export
SharedModule
中的 Directive
和 import
[=31 中的 SharedModule
=],但你在另一个 NgModule
中使用了 Directive
,它没有 import
SharedModule
也没有 import
AppModule
,因此不了解你的 Directive
。
所以要在 NgModule
中使用某些东西,它需要 declare
它,import
声明 NgModule
或 import
NgModule
,其中 import
声明 NgModule
。
仅当声明 NgModule
导出 Directive
.
时导入才有效
我似乎无法让我的指令起作用,想知道这是否是由于使用了 *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';
}
}
组件 HTML 中需要 *ngIf,因为我正在 ngOnInit 上从 JSON 服务收集数据。
为简洁起见忽略了代码:我正在将指令添加到导出指令的 "shared" 模块中。然后将此模块导入到主应用程序模块中。
这是已知问题还是我的代码?
更新 我现在可以正常工作了,但是我必须将指令导入到包含该组件的模块中。我可以不将它导入 AppModule 然后全局使用吗?
Angular
模块系统是这样工作的:
- 您需要
declare
一个Component
/Directive
/... 在一个NgModule
.
中 然后您可以在属于此NgModule
的Component
中使用它。 - 要在任何其他
NgModule
中使用Component
/Directive
/...,您需要export
它来自声明NgModule
和import
在NgModule
中要使用它的地方声明NgModule
。
在你的情况下你 declare
和 export
SharedModule
中的 Directive
和 import
[=31 中的 SharedModule
=],但你在另一个 NgModule
中使用了 Directive
,它没有 import
SharedModule
也没有 import
AppModule
,因此不了解你的 Directive
。
所以要在 NgModule
中使用某些东西,它需要 declare
它,import
声明 NgModule
或 import
NgModule
,其中 import
声明 NgModule
。
仅当声明 NgModule
导出 Directive
.