如何在Angular中通过ng-content显示指定序号的投影内容?
如何在Angular内容投影中按序号显示指定内容
我在Angular中创建了支持内容投影的自定义组件:
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-box', template: '<ng-content select="[body]"></ng-content>', }) export class BoxComponent { constructor() {} }
在application.component.html中使用:
<app-box> <div body>1</div> </app-box>
此时能正常显示数字1。现在我想传入数量不固定的内容项,并在组件中按序号选择性显示,比如只显示第二个内容项(数字2)。我尝试给ng-content的select加上:nth-of-type(2),但没达到预期效果:
修改后的app-box组件:
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-box', template: '<ng-content select="[body]:nth-of-type(2)"></ng-content>', }) export class BoxComponent { constructor() {} }
使用代码:
<app-box> <div body>1</div> <div body><b>2</b></div> <div body><i>3</i></div> </app-box>
请问该如何实现按序号显示指定的投影内容?
解决方案
方法一:使用准确的CSS选择器匹配
Angular的ng-content支持CSS选择器,但:nth-of-type是基于元素的原始类型位置匹配,而非带指定属性元素的相对位置。你需要改用:nth-child来选中带body属性的第n个子元素:
修改app-box的模板:
<ng-content select="[body]:nth-child(2)"></ng-content>
这样就能精准匹配第二个带body属性的元素,显示数字2。
方法二:通过输入属性动态控制显示索引
如果需要更灵活的动态切换(比如根据业务逻辑调整显示序号),可以结合ViewChildren和组件输入属性实现:
- 修改
app-box组件:
import { Component, Input, ViewChildren, QueryList, ElementRef, AfterContentInit } from '@angular/core'; @Component({ selector: 'app-box', template: ` <ng-container *ngFor="let item of projectedItems; let i = index"> <div *ngIf="i === displayIndex" [innerHTML]="item.nativeElement.innerHTML"></div> </ng-container> `, }) export class BoxComponent implements AfterContentInit { @Input() displayIndex = 0; // 默认显示第一个元素(索引从0开始) @ViewChildren('bodyItem') projectedItems!: QueryList<ElementRef>; ngAfterContentInit() { // 内容投影完成后可获取所有目标元素 } }
- 使用时传入目标索引:
<app-box [displayIndex]="1"> <!-- 索引1对应第二个元素 --> <div #bodyItem>1</div> <div #bodyItem><b>2</b></div> <div #bodyItem><i>3</i></div> </app-box>
这种方法支持动态调整显示内容,适合需要交互切换的场景。
内容的提问来源于stack exchange,提问作者Tom Smykowski
相关产品推荐
相关产品推荐

