angular踩坑之自定义组件

需求如下:

1 三个组件,这三个组件分别是祖组件grand,parent和child,grand引入parent,parent引入child

2 页面prods引入grand,形成这样的关系

prods 》grand 》parent 》child

3 grand 》parent 》child这三个组件不能作为全局组件。

实现:

1 app.module.ts中引入 prodsModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes, UrlSerializer } from '@angular/router';
import { AppComponent } from './app.component';
import { NZ_I18N } from 'ng-zorro-antd/i18n';
import { zh_CN } from 'ng-zorro-antd/i18n';
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';

import { ProdsComponent } from './pages/prods/prods.component';
import { ProdsModule } from './pages/prods/prods.module';

registerLocaleData(zh);

@NgModule({
    declarations: [
        ProdsComponent
    ],
    providers: [
        { provide: [NZ_I18N, UrlSerializer], useValue: zh_CN },
        { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorInterceptor, multi: true },
 
    ],
    bootstrap: [AppComponent],
    imports: [
        ProdsModule,
    ]
})
export class AppModule { }

2 prods.module.ts中引入三个组件。同时在exports中配置这三个组件。()这是关键

import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GrandComponent } from '../../components/grand/grand.component';
import { ParentComponent } from '../../components/parent/parent.component';



@NgModule({
  declarations: [GrandComponent,ParentComponent],
  imports: [
    CommonModule
  ],
  exports:[GrandComponent,ParentComponent] //这里是重点
})
export class ProdsModule { }

如果不配置exports选项会报错:

'app-grand' is not a known element: 1. If 'app-grand' is an Angular component, then verify that it is part of this module. 2. If 'app-grand' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. 3

3 由于prodsModules中引入了这三个组件,所以尽管grand的html中直接引入

,parent组件的html中直接引入都不会报错

你可能感兴趣的:(angular.js,前端,javascript)