Angular中<select>组件的选项禁用与字体颜色设置咨询
解决方案
核心问题分析
你的代码存在两个关键问题:一是用全局变量控制所有行的禁用状态,导致无法独立控制每行下拉框;二是禁用逻辑写反,且未实现选中ERR时禁用FIN的需求;同时缺少状态字体颜色的动态设置逻辑。
修改后的代码实现
1. Component.ts 代码
control: Control[] = []; controlModel: Control = new Control(); estadoModel: Estatus[] = []; constructor(private controlService: ControlService) { } ngOnInit(): void { this.obtenerListaControl(); this.obtenerListaEstado(); } private obtenerListaControl(){ this.controlService.obtenerControl().subscribe(response => { this.control = response.data; // 初始化每行的状态属性,避免ngModel绑定报错 this.control.forEach(item => { if (!item.cveEstado) item.cveEstado = ''; }); }); } private obtenerListaEstado(){ this.controlService.obtenerEstatus().subscribe(resp => { this.estadoModel = resp.data; }); } // 可选:下拉框切换时的额外逻辑 onChangeList(e, contr){ console.log("当前行选中状态:::::" + contr.cveEstado); } // 获取状态对应的字体颜色 getEstadoColor(estado: string): string { switch(estado) { case 'FIN': return 'black'; case 'INP': return 'blue'; case 'ERR': return 'red'; default: return 'black'; } } guardar(){ // 这里建议根据实际需求调整:如果是批量修改,遍历control数组提交;如果是单条,需传入当前行数据 this.controlService.updateEstado(this.controlModel).subscribe(data=>{ this.controlModel=data; }) }
2. HTML 模板代码
<button type="submit" class="btn btn-primary" (click)="guardar()">Guardar</button> <table class="table table-striped"> <thead> <tr> <th scope="col">ID</th> <th scope="col">ESTADO</th> <th scope="col">COMENTARIO</th> <th scope="col">HORA INICIO</th> </tr> </thead> <tbody> <tr *ngFor="let contr of control"> <td>{{contr.id}}</td> <td> <select class="select" [(ngModel)]="contr.cveEstado" (change)="onChangeList($event, contr)" [style.color]="getEstadoColor(contr.cveEstado)"> <option *ngFor="let estatus of estadoModel" [value]="estatus.cveEstado" [disabled]="contr.cveEstado === 'ERR' && estatus.cveEstado === 'FIN'"> {{estatus.descripcionEstado}} </option> </select> </td> <td>{{contr.comentario}}</td> <td>{{contr.horaInicio}}</td> </tr> </tbody> </table>
关键修改说明
- 独立状态跟踪:使用
[(ngModel)]="contr.cveEstado"双向绑定每行的状态,替代全局变量,确保每行下拉框的状态互不干扰。 - 正确禁用逻辑:通过
[disabled]="contr.cveEstado === 'ERR' && estatus.cveEstado === 'FIN'"实现:仅当当前行选中ERR时,禁用FIN选项,其他状态下所有选项正常可用。 - 动态字体颜色:通过
[style.color]="getEstadoColor(contr.cveEstado)"根据当前选中状态自动切换字体颜色,也可以改用类绑定(定义CSS类后用[ngClass])实现相同效果。 - 语法错误修正:修复了模板中
{{contr.comentario}}的闭合语法错误,移除了无效的全局isDisabled变量。
内容的提问来源于stack exchange,提问作者Root93
相关产品推荐
相关产品推荐

