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

Angular组件中@if块内<ng-content>无法显示的问题求助

问题原因

Angular 的 <ng-content> 内容投影机制是单次绑定的:组件初始化时,父组件投影的内容会被分配给第一个被渲染的 <ng-content> 实例。当你的条件分支切换时,另一个分支的 <ng-content> 因为没有可投影的内容(已被第一个实例占用),所以会显示为空——哪怕第一个 <ng-content> 已经被销毁,投影内容也不会自动重新分配。

在你的代码中,当屏幕宽度大于768时,@else 分支的 <ng-content> 先渲染并捕获了投影内容;后续切换到宽度≤768且open()为true的分支时,新的 <ng-content> 没有内容可投影,因此无法显示。

解决方法

用 <ng-template> 捕获投影内容,再通过 <ng-container *ngTemplateOutlet> 在条件分支中复用这个模板,避免多次使用 <ng-content> 导致的内容丢失:

<app-header />
<div class="container">
  <!-- 先将投影内容捕获到模板中 -->
  <ng-template #projectedContent>
    <ng-content />
  </ng-template>

  @if (innerWidth <= 768) {
    @if (open()) {
      <div class="container2" style="width: 450px; z-index: 15;">
        <!-- 复用模板内容 -->
        <ng-container *ngTemplateOutlet="projectedContent"></ng-container>
      </div>
    }
  } @else {
    <!-- 复用模板内容 -->
    <ng-container *ngTemplateOutlet="projectedContent"></ng-container>
  }
  <app-map />
</div>
额外检查点
  • 确保 open() 是 Angular 信号(Signal)或可观察对象(Observable),这样它的返回值变化能触发视图更新。如果是普通函数,Angular 可能无法检测到值的变化,导致条件不生效。
  • 确认 innerWidth 会在窗口 resize 时正确更新,比如使用 HostListener 监听 resize 事件:
    import { Component, HostListener } from '@angular/core';
    
    @Component({...})
    export class YourComponent {
      innerWidth: number = window.innerWidth;
    
      @HostListener('window:resize')
      onResize() {
        this.innerWidth = window.innerWidth;
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 10:05:15