9

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

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What purpose does the template variable filePicker serve here?
If you hide the input (display: none) you can create a custom button and then call filePicker.click() to start handling the file upload.
patchValue doesn't work for me : TS2322: Type File is not assignable to type null | undefined I had to use the UntypedFormGroup so I could initiate will a null value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.