如何将数组数据填充到多个独立mat-form-field表单控件中?
问题解决步骤
1. 修复HTML中重复的FormControlName
你的HTML代码里,关闭组(off)的输入框误用了和开启组(on)相同的formControlName,这会导致表单控件绑定冲突,无法正确渲染值。修改后的HTML代码如下:
<div class="on"> <mat-form-field appearance="fill" class="time_field"> <mat-label>minute</mat-label> <input matInput type="number" formControlName="minute_glow_periodic" min="0" max="59"> </mat-form-field> <mat-form-field appearance="fill" class="time_field"> <mat-label>hour</mat-label> <input matInput type="number" formControlName="hour_glow_periodic" min="0" max="24"> </mat-form-field> </div> <div class="off"> <mat-form-field appearance="fill" class="time_field"> <mat-label>minute</mat-label> <input matInput type="number" formControlName="minute_silence_periodic" min="0" max="59"> </mat-form-field> <mat-form-field appearance="fill" class="time_field"> <mat-label>hour</mat-label> <input matInput type="number" formControlName="hour_silence_periodic" min="0" max="24"> </mat-form-field> </div>
2. 正确初始化表单并绑定periodicValues数据
确保periodicValues数据可用后,再完成表单初始化或赋值操作,分两种场景处理:
场景一:periodicValues为同步初始数据
直接用数组值初始化表单控件:
// 示例初始数据:[开启小时, 开启分钟, 关闭小时, 关闭分钟] periodicValues: number[] = [8, 30, 22, 0]; ngOnInit(): void { this.form = this.formBuilder.group({ hour_glow_periodic: new UntypedFormControl(this.periodicValues[0], { disabled: false }), minute_glow_periodic: new UntypedFormControl(this.periodicValues[1], { disabled: false }), hour_silence_periodic: new UntypedFormControl(this.periodicValues[2], { disabled: false }), minute_silence_periodic: new UntypedFormControl(this.periodicValues[3], { disabled: false }), }); }
场景二:periodicValues为异步获取数据
先初始化空表单,待数据返回后用patchValue填充:
ngOnInit(): void { // 先初始化空表单结构 this.form = this.formBuilder.group({ hour_glow_periodic: new UntypedFormControl(null, { disabled: false }), minute_glow_periodic: new UntypedFormControl(null, { disabled: false }), hour_silence_periodic: new UntypedFormControl(null, { disabled: false }), minute_silence_periodic: new UntypedFormControl(null, { disabled: false }), }); // 模拟异步获取数据(如接口请求) this.yourDataService.getPeriodicValues().subscribe((data) => { this.periodicValues = data; // 填充表单值 this.form.patchValue({ hour_glow_periodic: this.periodicValues[0], minute_glow_periodic: this.periodicValues[1], hour_silence_periodic: this.periodicValues[2], minute_silence_periodic: this.periodicValues[3], }); }); }
3. 提交时更新periodicValues数组
在提交按钮的点击事件中,从表单提取最新值更新数组:
onSubmit(): void { if (this.form.valid) { const formValues = this.form.value; this.periodicValues = [ formValues.hour_glow_periodic, formValues.minute_glow_periodic, formValues.hour_silence_periodic, formValues.minute_silence_periodic, ]; // 执行后续提交逻辑(如接口请求) } }
内容的提问来源于stack exchange,提问作者Rezvaneh Aftabgard
相关产品推荐
相关产品推荐

