Angular中如何使用ng-content修改投影内容,按输入字符数截取显示?
实现步骤
1. 核心思路
因为<ng-content>仅做内容投射,无法直接修改内容,所以我们需要先获取投影内容的原始文本,按输入的字符数截取后再主动渲染。
2. 完整实现代码
text.component.ts
import { Component, Input, ContentChild, ElementRef, AfterContentInit, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-text-component', template: `<span>{{ processedText }}</span>`, }) export class TextComponent implements AfterContentInit, OnChanges { // 输入的截取字符数 @Input() characterCount!: number; // 自动获取投影的根元素,无需手动给投影内容加模板变量 @ContentChild('*', { read: ElementRef }) projectionRoot!: ElementRef<HTMLElement>; processedText = ''; private originRawText = ''; ngAfterContentInit(): void { // 初始化时获取原始投影文本 if (this.projectionRoot?.nativeElement) { this.originRawText = this.projectionRoot.nativeElement.textContent?.trim() || ''; this.updateSliceText(); } } ngOnChanges(changes: SimpleChanges): void { // 字符数参数变化时重新截取 if (changes['characterCount'] && this.originRawText) { this.updateSliceText(); } } private updateSliceText(): void { if (this.characterCount <= 0 || this.originRawText.length <= this.characterCount) { this.processedText = this.originRawText; return; } // 截取指定长度,可根据需求自行拼接省略号等后缀 this.processedText = this.originRawText.slice(0, this.characterCount); } }
父组件调用写法
和你给出的示例完全兼容,不需要额外修改调用代码:
<app-text-component characterCount="5"> <span> Hello World </span> </app-text-component>
最终渲染结果为Hello,符合需求。
3. 注意事项
- 如果需要保留投影内容的原HTML标签和样式,可将模板的插值写法改为
[innerHTML]="processedHtml",遍历原始投影的DOM节点修改文本内容后再赋值,注意做好XSS防护,避免渲染不可信的用户输入内容 - 如果需要支持动态修改投影内容,可把
ngAfterContentInit换成ngAfterContentChecked,实时监听投影内容的变化
内容的提问来源于stack exchange,提问作者Ankit Choudhary
相关产品推荐
相关产品推荐

