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

Angular中ngIf反向显示异常:条件为真时对应内容不展示

问题解决:Angular条件模板不显示的问题
  • 问题根源:Angular模板上下文默认绑定组件实例,访问组件类属性时不需要加this.。你代码里的this.showThis会被解析为模板上下文里的this变量(而非组件实例的属性),导致showThis为true时条件判断失效,第一个模板无法渲染。

  • 修正后的代码(保留你原有的双ng-template结构):

<mat-checkbox class="med-checkbox" (change)="onChange($event)" [checked]="protocol.showInProtocol">
  <ng-template *ngIf="showThis; else elseContent">
    String goes here
  </ng-template>
  <ng-template #elseContent>
    Else goes here
  </ng-template>
</mat-checkbox>
  • 更简洁的写法(无需额外嵌套ng-template):
<mat-checkbox class="med-checkbox" (change)="onChange($event)" [checked]="protocol.showInProtocol">
  <span *ngIf="showThis; else elseContent">String goes here</span>
  <ng-template #elseContent>Else goes here</ng-template>
</mat-checkbox>
  • 另一种显式绑定写法(不用*语法糖):
<mat-checkbox class="med-checkbox" (change)="onChange($event)" [checked]="protocol.showInProtocol">
  <ng-template [ngIf]="showThis" [ngIfElse]="elseContent">
    String goes here
  </ng-template>
  <ng-template #elseContent>
    Else goes here
  </ng-template>
</mat-checkbox>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:12:06