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

Angular中ngIf与ng-template配合异常:始终显示空模板求助

Angular通知弹出框渲染异常问题及解决办法

我正在实现一个通知弹出框,需求是有新通知时展示所有新通知,无新通知时展示空提示。但使用*ngIf和ng-template进行渲染时,即使ts文件中emptyNotification设为false,页面仍始终显示空模板。

问题代码

HTML代码

<div class="popup_over" *ngIf="!emptyNotification; else emptyNotification">
    // 通知列表代码
</div>

<ng-template #emptyNotification>
     // 空提示代码
</ng-template>

TypeScript代码

...

emptyNotification = false;

...

问题解决

问题已解决!原因是模板引用名称#emptyNotification与TS文件中的布尔变量emptyNotification重名了——Angular解析时,模板引用变量的优先级高于组件类中的变量,导致*ngIf的条件判断逻辑完全出错,不管变量值是true还是false,都会指向空模板。

另外也可以用ng-container方案实现需求,只要保证变量名和模板引用名不冲突即可:

<ng-container *ngIf="!isEmptyNotification; else emptyTpl">
  <div class="popup_over">
    // 通知列表代码
  </div>
</ng-container>

<ng-template #emptyTpl>
  // 空提示代码
</ng-template>

对应的TS变量修改为不冲突的名称:

isEmptyNotification = false;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:03:21