ngAfterViewInit not patching the form's values

299 Views Asked by At

I want to set the form's value with something that I have stored in the localStorage. The output of the console in the ngAfterViewInit() function shows a value existing for monthlyHoursName. The output for the values of the form is {}, i.e. an empty object. I think I am missing something, but I thought ngAfterViewInit() was being called after the form is initialized.

export class MonthlyHoursComponent implements AfterViewInit {
  ...
  @ViewChild('workDayHourForm') workDayHourForm: NgForm;
  constructor() {}

  ngAfterViewInit(): void {
    this.workDayHourForm.form.patchValue({
      name: localStorage.getItem('monthlyHoursName') || '',
      hours: 0,
    });
    console.log(
      'localStorage.getItem("monthlyHoursName")',
      localStorage.getItem('monthlyHoursName')
    );
    console.log(
      'this.workDayHourForm.form.getRawValue()',
      this.workDayHourForm.form.getRawValue()
    );
  }
  ...
}

The HTML for the component:

<div class="main-container">
  <div class="monthly-form">
    <mat-card>
      <mat-card-content>
        <form
          #workDayHourForm="ngForm"
          (ngSubmit)="addWorkday(workDayHourForm)"
        >
          <h2>Working Hours Tracker</h2>
          <div class="row">
            <div class="col-md-6">
              <mat-form-field appearance="outline">
                <mat-label>Name</mat-label>
                <input
                  matInput
                  name="name"
                  ngModel
                  [disabled]="fixedNameMonthYear"
                />
              </mat-form-field>
            </div>
            <div class="col-md-6">
              <mat-form-field appearance="outline">
                <mat-label>Month and Year</mat-label>
                <input
                  name="monthYear"
                  matInput
                  (click)="dp.open()"
                  [(ngModel)]="monthYear"
                  [matDatepicker]="dp"
                  [disabled]="fixedNameMonthYear"
                />
                <mat-datepicker-toggle
                  matIconSuffix
                  [for]="dp"
                  [disabled]="fixedNameMonthYear"
                ></mat-datepicker-toggle>
                <mat-datepicker
                  #dp
                  [disabled]="fixedNameMonthYear"
                  startView="year"
                  (monthSelected)="setMonthAndYear($event, dp)"
                  panelClass="example-month-picker"
                >
                </mat-datepicker>
              </mat-form-field>
            </div>
            <div class="col-md-6">
              <mat-form-field appearance="outline">
                <mat-label>Day</mat-label>
                <input
                  name="dayOfMonth"
                  matInput
                  ngModel
                  type="number"
                  min="1"
                  max="31"
                />
              </mat-form-field>
            </div>
            <div class="col-md-6">
              <mat-form-field appearance="outline">
                <mat-label>Hours</mat-label>
                <input
                  name="hours"
                  ngModel
                  matInput
                  type="number"
                  min="0"
                  max="400"
                />
              </mat-form-field>
            </div>
          </div>
          <div class="form-btn">
            <button mat-raised-button color="primary" type="submit">
              Add To List
            </button>
          </div>
        </form>
      </mat-card-content>
    </mat-card>
  </div>
  <div class="add-list">
    <app-monthly-hour-table
      #workTable
      (workItemsChanged)="disableCheckNameMonthYear()"
    ></app-monthly-hour-table>
  </div>
  <div class="form-btn">
    <button mat-raised-button color="primary">Submit List</button>
  </div>
</div>
2

There are 2 best solutions below

1
Harshit T On

Try using this.workDayHourForm.patchValue({... instead of this.workDayHourForm.form.patchValue({.... if you are putting #workDayHourForm on the form element in the template.

3
Aman Gojariya On

If you are using Template Driven Form then you need to use below code for patch value

this.workDayHourForm.control.patchValue({
   name: localStorage.getItem('monthlyHoursName') || '',
   hours: 0,
});

If you are using Reactive Form then you need to use below code

this.workDayHourForm.patchValue({
   name: localStorage.getItem('monthlyHoursName') || '',
   hours: 0,
});