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 .
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;
}
remove formControlName="image" and replace it with (change)="onChangeImage()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With