【问题标题】:Angular2 - Directive not working when not declared in the same moduleAngular2 - 未在同一模块中声明时指令不起作用
【发布时间】:2017-06-27 12:42:51
【问题描述】:

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

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

  ...
}

如果ModalDirective 未在MyModule 中声明,则MyComponent 中的modalundefined(即使在ngAfterViewInit 中)。任何人都知道如何解决这个问题?

【问题讨论】:

    标签: angular angular2-directives angular2-modules viewchild


    【解决方案1】:

    在你的SharedModule 中你需要export ModalDirective

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

    有关更多信息,请参阅共享模块上的 docs

    【讨论】:

    • 谢谢弗雷德里克!我的指令注入了TemplateRef。但是,当我将指令添加到 NgModule.exports 列表中时,我收到一条错误消息,显示为 No provider for TemplateRef!。有什么想法吗?
    • @cosmozhang - 没有看到你的代码就无法真正分辨,但看看这个线程:stackoverflow.com/questions/35932074/…
    • 对我来说,即使将其添加到导出中也不起作用
    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 2018-01-28
    • 2017-05-16
    • 2016-07-10
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多