[Fixed] Angular Set value to MatInput type time

Issue

I have a matInput field of type time which I want to set the HH:mm of a new Date () variable, when I use [value] I can do it, but I would like to know how to do it using formControlName.

component.html

            <mat-form-field appearance="outline" class="pl-sm-8 no-errors-spacer" fxFlex="50">
                <mat-label>Time:</mat-label>
                <input matInput
                       type="time"
                       formControlName="Time_start" 
                required>
            </mat-form-field>

component.ts

      createComposeForm(): FormGroup
      {
        return this._formBuilder.group({
          Time_start : [''],
        });
      }

      ngOnInit(): void
      {
        this.form = this.createComposeForm();
        let fechaInicioValue = new Date(this.VarWhitTheDate);
        this.form.get('Time_start').setValue(= new Date(fechaInicioValue ););
       }

Solution

Your HTML is OK. And make sure your form-field is nested under form.

And you have to convert your date to time string to work.

So, setting the value will look like:

this.form.get("Time_start").setValue(this.getTimeAsString(fechaInicioValue));

The conversion function:

getTimeAsString(date: Date) {
    return `${date.getHours()}:${(date.getMinutes() < 10 ? "0" : "") +
      date.getMinutes()}`;
  }

Working solution at StackBlitz

Leave a Reply

(*) Required, Your email will not be published