Angular调用patchValue无法为mat-select正常设置选中值
问题产生原因
核心问题是Angular Material Select 做选项匹配时使用严格相等(===)判断,你当前绑定的选项值和接口返回值类型不匹配:
- 模板中
mat-option使用[value]="0"这类方括号绑定写法,Angular会将引号内的内容作为JS表达式求值,最终绑定的选项值是数字类型(0、1、2、3) - 数据库接口返回的
result.organization是字符串类型(比如返回"1"而非数字1),虽然控制台打印内容看起来一致,但"1" !== 1,组件找不到匹配的选项,自然无法完成选中状态映射。
你可以在控制台执行console.log(typeof result.organization)验证,返回值会是string,和选项的数字类型不匹配。
修复方案
两种方案任选其一即可,核心是保证选项绑定值和表单赋值的类型、值完全一致:
方案1:将选项值改为字符串类型(改动最小)
去掉value属性的方括号绑定,直接写字符串字面量,和接口返回的字符串类型对齐:
<mat-label>Select an option</mat-label> <mat-select formControlName="organization"> <mat-option value="0">None</mat-option> <mat-option value="1">Bank Operations (Mike Conticello)</mat-option> <mat-option value="2">Brokerage product Services (Kent Clark)</mat-option> <mat-option value="3">Custody & Asset Services ( Staci Sullivan)</mat-option> </mat-select>
说明:不带方括号的
value="xxx"写法,绑定的是原生字符串属性值,不会做表达式求值,和接口返回的字符串类型完全匹配。
方案2:赋值时将返回值转为数字类型
保留模板中数字类型的选项绑定,在调用patchValue前把organization字段转为数字,和选项值类型对齐:
this.nominationSvc.GetNominationById(this.id) .then( result => { if (result != null) { console.log(result.organization); // 字段类型转换为数字 result.organization = Number(result.organization); this.nominationForm.patchValue(result); } } );
内容的提问来源于stack exchange,提问作者veena panakanapalli
相关产品推荐
相关产品推荐

