Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failed to set the 'value' property on 'HTMLInputElement' in reactive form

In the form of a data record, I upload a picture, the image will be uploaded to a server folder and its name will be stored in the database.

in this editing form i get the file name from server and i need to fill <input type="file"> in this form . using the reactive form in angular6 .

this is my code in ts file :

   ngOnInit() {
  this.EditForm=this.fb.group({
  imageName:['',Validators.compose([Validators.required])]
})
this.SetForm(this.dat)
}

  SetForm(dt:data){
   this.EditForm.setValue({imageName:[dt.imageName]});
  }

in html :

<form [formGroup]="EditForm">
    <input type="file" #file formControlName="imageName">
</form>

and this is my code : stackblitz

i not idea for this problem , and i have 3 days have problem , please see my code and change that for solve this problem .

like image 201
Mr-Programer Avatar asked Sep 02 '25 11:09

Mr-Programer


2 Answers

For security reasons, it's possible to set programmatically only an empty string to a file input value to clear the selection. If you set a value to input with type file, you'll get an error like:

ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement': 
This input element accepts a filename, which may only be programmatically set 
to the empty string.

As a workaround for modern browsers, DataTransfer might be used for changing file input value:

HTML (based on stackblitz):

<form [formGroup]="EditForm">
  <input id="my-input" type="file">
</form>

<button (click)="changeFileName()">Change File Name</button>

Component:

changeFileName() {
  const dataTransfer = new ClipboardEvent('').clipboardData || new DataTransfer();
  dataTransfer.items.add(new File(['my-file'], 'new-file-name'));
  const inputElement: HTMLInputElement = document.getElementById('my-input') as HTMLInputElement

  inputElement.files = dataTransfer.files;
}
like image 125
Vadi Avatar answered Sep 04 '25 00:09

Vadi


remove formControlName="image" and replace it with (change)="onChangeImage()"

like image 22
Mohamed Abo Elmagd Avatar answered Sep 04 '25 01:09

Mohamed Abo Elmagd