Angular8中共享模块,共享组件的写法(anular其他模块组件引用方法)

Angular8中共享模块,共享组件的写法(anular其他模块组件引用方法)

第一步:全局创建一个共享的module

这里示例创建一个模块common-share
创建完成后,会生成两个文件
文件1:common-share-routing.module.ts
文件2:common-share.module.ts

第二步:我们在模块下创建一个需要共享的组件

这里示例创建一个组件common-form-share-new
创建完成后会,会生成三个文件或者两个文件
文件1:common-form-share-new.component.html
文件2:common-form-share-new.component.less
文件3:common-form-share-new.component.ts

第三步:

打开模块里这个文件common-share.module.ts
根据下面代码进行操作:

import { NgModule } from '@angular/core';
import { SharedModule } from '@shared';
import { CommonShareRoutingModule } from './common-share-routing.module';
import { CommonFormShareNewComponent } from './common-form-share-new/common-form-share-new.component'; // 这里是共享的组件 

const COMPONENTS = [];
const COMPONENTS_NOROUNT = [];

@NgModule({
  imports: [
    SharedModule,
    CommonShareRoutingModule
  ],
  declarations: [
    ...COMPONENTS,
    ...COMPONENTS_NOROUNT,
    CommonFormShareNewComponent //这里引入共享的组件 
  ],
  exports:[CommonFormShareNewComponent], // 把共享的组件放入到导出的出口中 
  entryComponents: COMPONENTS_NOROUNT
})
export class CommonShareModule { }

第四步:

去到你想要引入组件的地方所在模块,比如我的父组件在这个模块 my-parent-module
进入my-parent-module.module.ts
根据下面代码进行操作:

import { NgModule } from '@angular/core';
import { SharedModule } from '@shared';
import { myParentModuleRoutingModule } from './maintain-system-sur-routing.module';
import { XXXXComponent} from './nand-size-maintain/XXXX.component';
import { CommonShareModule } from '../common-share/common-share.module'; // 这句是需要添加的代码
const COMPONENTS = [];
const COMPONENTS_NOROUNT = [];

@NgModule({
  imports: [
    SharedModule,
    myParentModuleRoutingModule,
    CommonShareModule // 共享模块--这句是需要添加的代码
  ],
  declarations: [
    ...COMPONENTS,
    ...COMPONENTS_NOROUNT,
    XXXXComponent
  ],
  entryComponents: COMPONENTS_NOROUNT
})
export class myParentModuleModule { }

第五步:在my-parent-module模块下的所有组件都可以随意引用这个共享组件啦~~

示例:
html代码:

<div>
  <app-common-form-share-new></app-common-form-share-new>
</div>
posted @ 2020-08-14 01:00  糖~豆豆  阅读(2144)  评论(0编辑  收藏  举报
Live2D