Angular2-未在同一模块中声明时指令不工作
我有一个指令,我想在多个模块中使用它。在每个模块上声明它会产生一个错误。因此,我尝试在共享模块中声明它,并将此共享模块导入其他模块。然而,它没有起作用。它仅在组件自己的模块上声明时才起作用 这是我的Angular2-未在同一模块中声明时指令不工作,angular,angular2-directives,angular2-modules,viewchild,Angular,Angular2 Directives,Angular2 Modules,Viewchild,我有一个指令,我想在多个模块中使用它。在每个模块上声明它会产生一个错误。因此,我尝试在共享模块中声明它,并将此共享模块导入其他模块。然而,它没有起作用。它仅在组件自己的模块上声明时才起作用 这是我的共享模块: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { GeneralDataService } from './general-data.ser
共享模块
:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GeneralDataService } from './general-data.service';
import {ModalDirective} from '../directives/modal.directive';
@NgModule({
imports: [
CommonModule
],
providers: [GeneralDataService],
declarations: [ModalDirective]
})
export class SharedModule { }
以及我要使用的模块ModalDirective
:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './patient.component';
import {SharedModule} from '../shared/shared.module';
@NgModule({
imports: [
CommonModule,
SharedModule
],
providers: [ ],
declarations: [ MyComponent ]
})
export class MyModule { }
在MyComponent
组件中:
export class MyComponent implements OnInit, AfterViewInit {
@ViewChild(ModalDirective) modal: ModalDirective;
...
}
如果
MyModule
中未声明ModalDirective
,则MyComponent
中的modal
是未定义的
(即使在ngAfterViewInit
)。有人知道怎么解决这个问题吗 在您的SharedModule
中,您需要导出ModalDirective
...
@NgModule{(
...
exports: [ModalDirective]
)}
export class SharedModule { ... }
有关更多信息,请参见共享模块上的Thx Fredrik!我的指令注入了TemplateRef
。但是,当我将该指令添加到NgModule.exports
列表中时,我得到一个错误,即没有TemplateRef的提供程序代码>。有什么想法吗?@cosmozhang-如果不看你的代码,我真的说不出来,但是看看这个线程:对我来说,即使在将它添加到导出后,它也不起作用