
angular 组件默认会忽略标签内部的内容,需通过 `
要在 Angular 自定义组件中支持“插槽式”内容插入(即类似 <app-mat-loading-card>...</app-mat-loading-card> 内部传入任意 HTML),必须显式启用内容投影(Content Projection) —— 这是 Angular 提供的标准机制,核心在于使用 <ng-content> 元素作为内容占位符。
✅ 正确实现步骤
-
在子组件模板(mat-loading-card.component.html)中添加 <ng-content>
将其放置在你希望外部内容渲染的位置。例如:<div class="main"> <div [ngClass]="{'parent': loading, 'parent-no-anim': !loading}"> <div class="child"> <!-- 外部传入的内容将在此处渲染 --> <ng-content></ng-content> </div> </div> </div> 确保组件无 encapsulation: ViewEncapsulation.ShadowDom 干扰(默认 Emulated 即可)
若使用 Shadow DOM,需额外注意样式穿透,但对内容投影本身无影响。-
父组件中按需使用(支持任意结构)
现在以下写法将正常生效:<app-mat-loading-card [loading]="device.loading || device.connecting"> <span class="button-title">{{ device.deviceName }}</span> <button (click)="onSelect(device)">Select</button> <img [src]="device.icon" alt="Device" width="24"> </app-mat-loading-card>浏览器中将真实渲染为:
<app-mat-loading-card ...> <div class="main"> <div class="parent"> <!-- 或 parent-no-anim --> <div class="child"> <span class="button-title">My Router</span> <button>Select</button> <img src="/icons/router.svg" width="24"> </div> </div> </div> </app-mat-loading-card>
⚠️ 注意事项
- <ng-content> 是编译时静态投影,不支持条件渲染(如 *ngIf 包裹 <ng-content> 无效);如需动态控制,应改用 @Input() 或 ng-template + ngTemplateOutlet。
- 支持多插槽投影:通过 select 属性实现(如 <ng-content select="[header]">),配合 <div header>...</div> 使用。
- 投影内容的样式作用域仍受父组件影响(因未进入 Shadow DOM),建议通过 ::ng-deep(已弃用,推荐 :host ::ng-deep 或 CSS 类隔离)或全局样式谨慎处理。
✅ 总结
内容投影不是“自动生效”的特性,而是需要开发者主动在子组件模板中声明 <ng-content> 才能启用。它是构建可复用、高内聚 UI 组件(如卡片、模态框、布局容器)的关键能力——既保持封装性,又提供灵活的内容定制入口。










