2017-02-09 15 views
6

我有一个指令,我想在多个模块中使用它。在每个模块上声明它会产生错误。因此,我试图在共享模块中声明它,并将此共享模块导入其他模块。但是,它没有工作。它仅在组件自己的模块上声明时才有效。Angular2 - 指令在未在同一模块中声明时不工作

这是我SharedModule

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; 

    ... 
} 

MyComponentmodalundefined(即使在ngAfterViewInit)如果ModalDirective未在MyModule中声明。任何人都知道如何解决此问题?

回答

10

在你SharedModule你需要exportModalDirective

... 

@NgModule{(
    ... 
    exports: [ModalDirective] 
)} 
export class SharedModule { ... } 

docs共享模块曾为更多信息

+0

。谢谢! –

+0

Thx Fredrik!我的指令注入了'TemplateRef'。但是,当我将该指令添加到'NgModule.exports'列表中时,出现错误提示“没有TemplateRef!提供程序”。有任何想法吗? – cosmozhang

+0

@cosmozhang - 无法看到您的代码真的不知道,但看看这个线程:https://stackoverflow.com/questions/35932074/angular2-no-provider-for-templateref-ngif-templateref –