Home > Enterprise >  Angular reactive forms patchValue does not work on ngbDatepicker input
Angular reactive forms patchValue does not work on ngbDatepicker input

Time:08-31

I'm patching my reactive form with data I receive from my backend.

 getUpdate(id: number) {
    this.httpService.getUpdate(this.environment, id).subscribe({
      next: (response: Update) => {
        this.update = response;

        this.updateForm.patchValue({
          channel: response.channel,
          updateTo: response.updateTo,
          updateOptionalUntil: response.updateOptionalUntil,
          setupFile: response.setupFile,
          information: response.information,
          md5: response.md5
        }) 
      }
    })
  }

This works fine if I have a "plain" text-field, like that:

<div >
     <span  for="updateOptionalUntil">Optional until</span>
     <input  id="updateOptionalUntil" type="text" formControlName="updateOptionalUntil">
</div>

Now, I would like to add a ngbDatepicker to update that input field, but as soon as I add it, my patch-value does not work anymore and the field stays empty when the component loads.

<div >
     <span  for="updateOptionalUntil">Optional until</span>
     <input  id="updateOptionalUntil" type="text" formControlName="updateOptionalUntil" ngbDatepicker #updateOptionalUntil="ngbDatepicker">
     <button  (click)="updateOptionalUntil.toggle()"><i ></i></button>
</div>

enter image description here

CodePudding user response:

As mentioned in the DOC.

Datepicker uses NgbDateStruct interface as a model and not the native Date object.

You should convert your string to NgbDateStruct format

 correctValue: NgbDateStruct ={
    year:2022,
    month:12,
    day:13
  };

Working Sample

  • Related