Angular2 - 未在同一模块中声明时指令不起作用

时间:2017-02-09 13:20:16

标签: angular angular2-directives angular2-modules viewchild

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

这是我的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;

  ...
}
如果modal中未声明MyComponent,则undefined中的ngAfterViewInitModalDirective(即使在MyModule中)。谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:14)

在您的SharedModule中,您需要export ModalDirective

...

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

有关详细信息,请参阅共享模块上的docs

相关问题