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é
相关产品推荐
相关产品推荐

