Upload Files using reactiveForms and FileUpload component angular
Asked Answered
B

1

7

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!!

Baur answered 1/12, 2022 at 17:13 Comment(0)
P
13

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.

Palgrave answered 1/12, 2022 at 18:5 Comment(2)
What purpose does the template variable filePicker serve here?Rampart
If you hide the input (display: none) you can create a custom button and then call filePicker.click() to start handling the file upload.Palgrave

© 2022 - 2024 — McMap. All rights reserved.