You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断ng-content选择器是否匹配内容?实现默认内容回退

判断带选择器的内容投影是否匹配并显示默认内容

要实现「有投影内容则显示,无则显示默认内容」的需求,你可以通过Angular的内容查询API检测是否有匹配选择器的投影内容,具体步骤如下:

1. 在组件类中获取投影内容的引用

使用@ContentChild或@ContentChildren装饰器,配合你的选择器[appChecklistTitle]获取投影元素的引用,以此判断是否有内容被投影进来。

静态场景(内容不会动态变化)

import { Component, ContentChild, ElementRef, OnInit } from '@angular/core';

@Component({
  selector: 'app-checklist',
  templateUrl: './checklist.component.html'
})
export class ChecklistComponent implements OnInit {
  // 通过属性选择器获取单份投影内容
  @ContentChild(ElementRef, { selector: '[appChecklistTitle]' }) projectedTitle?: ElementRef;
  hasProjectedContent = false;

  ngOnInit(): void {
    // 检查是否存在投影内容
    this.hasProjectedContent = !!this.projectedTitle;
  }
}

动态场景(内容可能动态添加/移除)

如果投影内容会动态变化,用@ContentChildren配合监听查询列表的变化:

import { Component, ContentChildren, QueryList, ElementRef, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-checklist',
  templateUrl: './checklist.component.html'
})
export class ChecklistComponent implements AfterContentInit {
  // 获取所有匹配选择器的投影内容
  @ContentChildren(ElementRef, { selector: '[appChecklistTitle]' }) projectedTitles!: QueryList<ElementRef>;
  hasProjectedContent = false;

  ngAfterContentInit(): void {
    this.updateContentStatus();
    // 监听投影内容的变化
    this.projectedTitles.changes.subscribe(() => this.updateContentStatus());
  }

  private updateContentStatus(): void {
    this.hasProjectedContent = this.projectedTitles.length > 0;
  }
}

2. 在模板中控制显示逻辑

根据组件类中hasProjectedContent的状态,决定显示投影内容还是默认内容,推荐使用ng-template让代码更清晰:

<!-- 显示投影内容 -->
<ng-container *ngIf="hasProjectedContent; else defaultContent">
  <ng-content select="[appChecklistTitle]"></ng-content>
</ng-container>

<!-- 默认内容模板 -->
<ng-template #defaultContent>
  <h3>默认清单标题</h3>
</ng-template>

也可以用简洁的双*ngIf写法:

<div *ngIf="hasProjectedContent">
  <ng-content select="[appChecklistTitle]"></ng-content>
</div>
<div *ngIf="!hasProjectedContent">
  <h3>默认清单标题</h3>
</div>

内容的提问来源于stack exchange,提问作者Gargoyle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:10:45