输入元素无法在 mat-form-field 中设置默认值

问题描述 投票:0回答:1

我希望

<mat-form-field>
中的输入元素具有默认值,但它不起作用!我测试了没有
<mat-form-field>
的输入,它工作正常。

.html

<mat-form-field appearance="fill" class="time_field">
    <mat-label>{{ minute | async}}</mat-label>
    <input matInput type="number" formControlName="minute_glow_periodic" value="4" min="0" max="60">
</mat-form-field>

.ts

this.form = this.formBuilder.group({
  minute_glow_periodic: new UntypedFormControl({ 
    value: this.data.element?.minute_glow_periodic,
    disabled: false 
  }),
});

get minuteGlowPeriodic() {
  return this.form.get('minute_glow_periodic') 
}

我希望我的输入元素有一个默认值,但没有一个解决方案有效!

html angular angular-material angular-reactive-forms mat-form-field
1个回答
2
投票

当您使用反应式表单时,不应使用

value
属性来设置默认值。

您应该在表单控件中设置默认值,这可以通过以下任一方法完成:

minute_glow_periodic: new UntypedFormControl({
  value: this.data.element?.minute_glow_periodic ?? 4,
  disabled: false,
})

if (!this.minuteGlowPeriodic!.value)
  this.minuteGlowPeriodic!.patchValue(4);

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.