Search code examples
angularangular-reactive-formsprimeng

Upload Files using reactiveForms and FileUpload component angular


I am using primeng for template. And I am using p-fileupload component, but I need to use it in reactive form, so I want to know where to put formControlName as I don't get any input or something label to add.

I only see it with input and put a identifier on it, but i want to know if it is possible on this component.

Any suggestions?

Thanks, in advice!!


Solution

  • First create your formGroup (reactive form)

    this.form = new FormGroup({
      title: new FormControl(""),
      image: new FormControl(null)
    });
    

    image is your image component (upload). So then inside your html:

    <input type="file" #filePicker (change)="onImagePicked($event)">
    

    So you can hide your input and simulate a click on it. But the onImagePicked function is important. Then back to the code behind:

    onImagePicked(event: Event) {
      const file = (event.target as HTMLInputElement).files[0]; // Here we use only the first file (single file)
      this.form.patchValue({ image: file});
    }
    

    And yes, that's all! You can use validators as well. All as normal FormControls.