简体   繁体   中英

Angular reactive forms patchValue does not work on ngbDatepicker input

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 class="input-group input-group-sm mb-2">
     <span class="input-group-text" for="updateOptionalUntil">Optional until</span>
     <input class="form-control" 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 class="input-group input-group-sm mb-2">
     <span class="input-group-text" for="updateOptionalUntil">Optional until</span>
     <input class="form-control" id="updateOptionalUntil" type="text" formControlName="updateOptionalUntil" ngbDatepicker #updateOptionalUntil="ngbDatepicker">
     <button class="btn btn-outline-dark" (click)="updateOptionalUntil.toggle()"><i class="fa-light fa-calendar-days"></i></button>
</div>

在此处输入图像描述

Maybe you are getting string response instead of date type, you can transform the response before calling patch value.

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: new Date(response.updateOptionalUntil), // <-  changed here
          setupFile: response.setupFile,
          information: response.information,
          md5: response.md5
        }) 
      }
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM