首页 文章

Angular 2/5在惰性模块中声明指令

提问于
浏览
0

我想在多个模块中重用一个指令 . 我无法在parentmodule中声明该指令,因为所有子模块都是通过延迟加载来加载的 . 如果我在两个子模块中声明相同的指令,我会收到一个错误:

错误错误:未捕获(在承诺中):错误:类型AddDirective是2个模块的声明的一部分:SharedModule和GdprModule!请考虑将AddDirective移动到导入SharedModule和GdprModule的更高模块 . 您还可以创建一个新的NgModule,它导出并包含AddDirective,然后在SharedModule和GdprModule中导入该NgModule .

AddDirective是一个简单的指令,为我提供动态组件所需的ViewContainerRef . 我按照以下教程添加它们:

https://angular.io/guide/dynamic-component-loader

我是否必须为每个惰性模块创建自己的指令,或者有没有办法通过共享模块提供相同的指令?

SharedModule:

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
     AddDirective
  ]
})

LazyModule:

import { SharedModule } from './pathToShared/sharaed.module';

@NgModule({
 imports: [ SharedModule ],
 declarations: [ LazyComponent],
 entryComponents: [ DynamicalComponent ]
})
export class LazyModule { }

2 回答

  • 0

    您可以创建共享模块 . 添加多次使用的模块并导出它们 . 例如

    shared.module.ts

    import { NgModule, ModuleWithProviders } from '@angular/core';
    import { CommonModule } from '@angular/common';
    
    import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
    import { AlertModule, TimepickerModule } from 'ngx-bootstrap';
    
    import { SweetAlertService } from './../sweetalert2.service';
    
    import { UnmaskDirective } from '../../directive/unmask.directive';
    import { FileUploadComponent } from '../file-upload/file-upload.component';
    
    @NgModule({
       imports: [
       CommonModule, NgbModule.forRoot(), AlertModule.forRoot(),TimepickerModule.forRoot(), FileUploadModule
      ],
      declarations: [UnmaskDirective, FileUploadComponent],
      providers: [SweetAlertService],
      exports: [
        NgbModule, AlertModule, TimepickerModule, UnmaskDirective, FileUploadComponent, FileUploadModule
      ]
    })
    export class SharedModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: SharedModule,
          providers: [SweetAlertService]
        }
      }
    }
    

    现在只要需要导入共享模块,例如register.module.ts

    import { SharedModule } from './../../common/sharaed/sharaed.module';
    
    @NgModule({
     imports: [ SharedModule ],
     declarations: [ UserComponent],
     entryComponents: []
    })
    export class RegisterModule { }
    

    现在注册模块具有共享模块中包含的所有模块

    你也可以参考这个链接shared.module.ts,_ angular real world example shared moduleangular-modules-feature-modules

  • 0

    创建一个共享模块并在其中添加指令并在app.module.ts中导入共享模块

相关问题