Angular中如何根据条件控制Mat Radio Group单选按钮的显示
解决方案
你可以通过两种方式实现根据schedule的值控制单选按钮的显示:
方法一:在模板中直接加条件判断
修改<mat-radio-button>标签,添加*ngIf控制显示逻辑:
<mat-radio-group [disabled]="!modelForm.get('schedule')?.value" [(ngModel)]="stage" layout="column"> <mat-radio-button *ngFor="let stage of stages" [value]="stage.text" color="primary" *ngIf="!(modelForm.get('schedule')?.value === '1' && stage.text !== 'A')" > {{ stage.text }} </mat-radio-button> </mat-radio-group>
逻辑说明:当schedule的值等于'1'时,仅显示text为'A'的按钮;其他场景两个按钮全部显示。用?.是为了避免modelForm.get('schedule')返回null时触发报错。
方法二:在TS中过滤数据源
在组件类里添加一个计算属性,根据schedule的值动态过滤stages数组:
stages = [ {id: 0, text: 'A'}, {id: 1, text: 'B'}, ]; get filteredStages() { const scheduleValue = this.modelForm.get('schedule')?.value; return scheduleValue === '1' ? this.stages.filter(stage => stage.text === 'A') : this.stages; }
然后修改模板,循环过滤后的数组:
<mat-radio-group [disabled]="!modelForm.get('schedule')?.value" [(ngModel)]="stage" layout="column"> <mat-radio-button *ngFor="let stage of filteredStages" [value]="stage.text" color="primary" > {{ stage.text }} </mat-radio-button> </mat-radio-group>
这种方式把显示逻辑收敛到TS中,模板更简洁,也方便后续扩展其他过滤规则。
内容的提问来源于stack exchange,提问作者Tim Launders
相关产品推荐
相关产品推荐

