Angular 17多内容投影报错NG8001:'profile-header'非已知元素
解决Angular 17多内容投影中'profile-header'未知元素报错问题
报错NG8001: 'profile-header' is not a known element的核心原因是:Angular默认会将自定义标签识别为Angular组件,但profile-header只是你用来做内容投影的标识,并没有对应的组件定义。可以通过以下两种方式解决:
方法一:配置自定义元素Schema
让Angular允许使用未定义的自定义标签,需要在ProfileComponent中添加CUSTOM_ELEMENTS_SCHEMA配置:
如果是独立组件,修改profile.component.ts:
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'], standalone: true, schemas: [CUSTOM_ELEMENTS_SCHEMA] // 添加该行配置 }) export class ProfileComponent {}
如果是NgModule组件,在对应的模块中配置:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ProfileComponent } from './profile.component'; @NgModule({ declarations: [ProfileComponent], exports: [ProfileComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA] // 添加该行配置 }) export class ProfileModule {}
方法二:改用属性选择器(推荐)
无需额外配置Schema,只需要修改内容投影的选择器为属性形式:
- 修改
profile.component.html中的ng-content选择器:
<div class="red"> <ng-content select="[profile-header]"></ng-content> </div> <div class="green"> <ng-content></ng-content> </div> <div class="blue"> <ng-content select="[profile-footer]"></ng-content> </div>
- 修改
app.component.html中的投影内容,把自定义标签改为带属性的元素:
<app-profile> <div profile-header><h2>Header 1</h2></div> <p>This is projected content</p> </app-profile>
两种方法都能解决报错,方法二更符合Angular默认的组件规范,无需额外配置Schema,推荐使用。
内容的提问来源于stack exchange,提问作者Ankur Mishra
相关产品推荐
相关产品推荐

