PatchValue for Upload file in angular

Viewed 1821

So i have edit form page like this enter image description here

and form a group like this

this.editMateri = this.fb.group({
  name: [''],
  description: [''],
  thumbnail: [null],
  isPublish: this.status,
  materialCreatorCode: [''],
  tags: this.selectedTags
});

and i fetch the data from the server and set the value to the form using patchValue like this

this.editMateri.patchValue(this.currentMateri);

everything works fine, but the problem is with the thumbnail File Upload input, by default it's null so if i update anything except the thumbnail, my thumbnail will goes blank, the thumbnail is set to null. I've been looking for stackblitz code for this but i didn't find any, anyone can help me?

EDIT

in my html like this

<div class="form-group">
    <label for="exampleInputEmail1" class="label">Thumbnail</label>
    <input type="file" nbInput fullWidth (change)="uploadFile($event)">
</div>

and for uploadFile function like this

  uploadFile(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.editMateri.patchValue({
      thumbnail: file
    });
    this.editMateri.get('thumbnail').updateValueAndValidity()
  }
1 Answers

I guess you have correctly added the formControlName for each of the fields. That's why everything works correctly.

But in the input for uploading the image for thumbnail, you have missed using formControlName.

Once you add that in your html, it should work correctly.

Please refer the following html code to be replaced.

<div class="form-group">
    <label for="exampleInputEmail1" class="label">Thumbnail</label>
    <input type="file" nbInput fullWidth formControlName="thumbnail" (change)="uploadFile($event)">
</div>
Related