Angular 14中如何在父组件中引用并展示嵌套子元素?
实现Angular 14支持多次展示嵌套内容的父组件
要让父组件能接收并多次渲染嵌套的普通元素或自定义子组件,你需要利用Angular的模板引用(TemplateRef)和模板输出(NgTemplateOutlet)——原生的<ng-content>只能投影内容一次,无法满足多次展示的需求。以下是两种实用实现方案:
方案一:显式模板方式(灵活可控)
这种方式需要用户将嵌套内容放在<ng-template>中,父组件通过模板引用获取内容并重复渲染。
1. 编写父组件类(my-parent.component.ts)
import { Component, ContentChild, TemplateRef } from '@angular/core'; @Component({ selector: 'app-my-parent', templateUrl: './my-parent.component.html', styleUrls: ['./my-parent.component.css'] }) export class MyParentComponent { // 获取用户传入的名为nestedContent的模板引用 @ContentChild('nestedContent') nestedContent!: TemplateRef<any>; }
2. 编写父组件模板(my-parent.component.html)
用*ngTemplateOutlet多次渲染获取到的模板内容:
<!-- 第一次展示嵌套内容 --> <div class="content-block"> <h4>区块一</h4> <ng-container *ngTemplateOutlet="nestedContent"></ng-container> </div> <!-- 第二次展示嵌套内容 --> <div class="content-block"> <h4>区块二</h4> <ng-container *ngTemplateOutlet="nestedContent"></ng-container> </div>
3. 使用父组件
用户只需将嵌套内容包裹在带#nestedContent标记的<ng-template>中:
<app-my-parent> <ng-template #nestedContent> <p>Hello World</p> <app-my-child></app-my-child> </ng-template> </app-my-parent>
方案二:隐式捕获内容(无需额外模板标记)
如果不想让用户编写<ng-template>,可以通过父组件内部的模板捕获默认投影内容,再重复渲染:
1. 编写父组件类(my-parent.component.ts)
import { Component, ViewChild, TemplateRef, AfterContentInit } from '@angular/core'; @Component({ selector: 'app-my-parent', templateUrl: './my-parent.component.html', styleUrls: ['./my-parent.component.css'] }) export class MyParentComponent implements AfterContentInit { @ViewChild('contentCapturer') contentCapturer!: TemplateRef<any>; // 存储捕获到的内容模板 capturedContent!: TemplateRef<any>; ngAfterContentInit() { this.capturedContent = this.contentCapturer; } }
2. 编写父组件模板(my-parent.component.html)
<!-- 第一次渲染内容 --> <div class="content-section"> <h4>第一部分内容</h4> <ng-container *ngTemplateOutlet="capturedContent"></ng-container> </div> <!-- 第二次渲染内容 --> <div class="content-section"> <h4>第二部分内容</h4> <ng-container *ngTemplateOutlet="capturedContent"></ng-container> </div> <!-- 内部模板,用于捕获用户传入的嵌套内容 --> <ng-template #contentCapturer> <ng-content></ng-content> </ng-template>
3. 使用父组件
用户可以直接在父组件标签内嵌套内容,无需额外模板标记:
<app-my-parent> <p>Hello</p> <app-my-child></app-my-child> </app-my-parent>
关键说明
- 不能用
{{ nestedContents }}渲染内容:插值表达式仅支持文本或简单数据绑定,无法渲染HTML元素或组件,必须使用模板相关API实现内容投影与重复渲染。 - 两种方案对比:显式模板方式支持传入多个不同模板,适合复杂场景;隐式方式更简洁,降低用户使用成本。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

