我似乎无法让我的指示工作,并想知道是否是由于使用了* 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。
为简洁而忽略了代码:我将指令添加到&#34;共享&#34;导出指令的模块。然后将此模块导入主应用程序模块。
这是一个已知问题还是我的代码?
更新我现在已经开始工作,但是我必须将指令导入到包含该组件的模块中。我可以不将其导入AppModule然后全局使用吗?
答案 0 :(得分:0)
Angular
模块系统的工作原理如下:
declare
Component
/ Directive
/ ...只需一NgModule
。Component
的{{1}}中使用它。 NgModule
中使用Component
/ Directive
/ ...,您需要NgModule
声明export
和NgModule
{1}}在您要使用它的import
中声明NgModule
。在您的情况下,您NgModule
和declare
export
中的Directive
以及SharedModule
import
SharedModule
,但您使用的是其他AppModule
中的Directive
,NgModule
import
而非SharedModule
import
,因此不知道您的AppModule
Directive
。
所以要在NgModule
中使用某些内容,需要declare
,import
声明NgModule
或import
a NgModule
,其中import
声明NgModule
仅当声明NgModule
导出Directive
。