Input element unable to set with default value in mat-form-field

167 views Asked by At

I want my input element in the <mat-form-field> to have a default value, but it doesn't work! I tested the input without <mat-form-field> and it works correctly.

.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') 
}

I expected my input element to have a default value but none of the solutions worked!

1

There are 1 answers

0
Yong Shun On BEST ANSWER

You shouldn't use the value attribute to set the default value as you are using Reactive Form.

You should set the default value in the form control, this can be done with either:

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

or

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

Demo @ StackBlitz