angular踩坑之自定义组件

发布时间:2024年01月19日

需求如下:

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 <app-grand></app-grand>

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

<app-parent></app-parent>,parent组件的html中直接引入<app-child></app-child>都不会报错

文章来源:https://blog.csdn.net/baidu_41601048/article/details/135700982
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。