代码之家  ›  专栏  ›  技术社区  ›  Present practice

在具有多个模块的Angular 6应用程序中共享一个组件

  •  0
  • Present practice  · 技术社区  · 6 年前

    我将一个大模块拆分为几个较小的模块,并出现以下问题: 1.搜索组件在多个组件之间使用。目前它是在app.module.ts中声明的。稍后,它将移动到shared.module.ts。 2.包装器组件使用搜索组件。当我创建simple wrapper.module.ts时,我得到一个错误,即app search不是已知元素。若我在wrapper.module.ts中声明它,我将得到一个错误,搜索组件在两个不同的模块中声明,这是有意义的。 CLI重新启动没有帮助。”“应用程序搜索”是正确的选择器名称。

    app.module.ts:

    import { CommonModule } from '@angular/common';
    import { NgModule } from '@angular/core';
    import { WrapperModule } from '../wrapper/wrapper.module';
    import { SearchComponent } from '../search/search.component';
    
    @NgModule({
     imports: [
      CommonModule,
      WrapperModule
     ],
     declarations: [
      AppComponent,
      SearchComponent
     ]
    })
    export class AppModule {}
    

    包装器模块:

    import { CommonModule } from '@angular/common';
    import { NgModule } from '@angular/core';
    import { WrapperComponent } from './wrapper.component';
    
    @NgModule({
      imports: [
       CommonModule
      ],
      declarations: [
       WrapperComponent
      ],
      exports: [
       WrapperComponent
      ],
     })
    export class WrapperModule {}
    

    Wrapper.component.html

    <app-search></app-search>
    

    搜索组件.ts

    @Component({
      selector: 'app-search',
      templateUrl: './search.component.html',
      styleUrls: ['./search.component.scss'],
    })
    ... 
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   MCMatan    6 年前

    如果要跨多个模块使用组件,则需要创建一个“共享”模块,并将该组件添加到共享模块的 exports . 然后将该共享模块添加到其他模块中 imports

    一旦你转身

        2
  •  1
  •   user10747134 user10747134    6 年前

    将搜索组件移动到共享模块(或共享功能模块)时,问题将得到解决。

    您不能像提供者一样使用它,在根目录中提供它允许模块内和模块下的所有单元访问它,因为它可能需要模块中的其他组件/etc。如果能够从父模块访问组件是可能的,那么当模块延迟加载时,事情可能会变得奇怪。

    另一种方法是只为一个共享组件或一组功能创建一个模块(看看 Angular Material

    推荐文章