Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2-未在同一模块中声明时指令不工作_Angular_Angular2 Directives_Angular2 Modules_Viewchild - Fatal编程技术网

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-如果不看你的代码,我真的说不出来,但是看看这个线程:对我来说,即使在将它添加到导出后,它也不起作用