I'm facing a challenge that I can't seem to figure out
It's a form structured in HTML like this:
<button (click)="addform()">add form</button>
<div class="conten-form">
<div class="MyForm">
<label>Name</label>
<input type="text" class="name">
<label>Description</label>
<input type="text" class="description">
<label>Photo</label>
<div class="img-cont">
<div class="img">
<img src="{{img}}">
</div>
<div class="addimg">
<input type="file" (change)="createimg($event)">
</div>
</div>
</div>
<div class="AddForm"></div>
<input type="buttom" value="send" (click)="sendform()">
</div>
This is how it looks in TS:
img : any; //to display
imgfile : any; //for form submission
constructor(...){...}
addform(){
let addform = document.querySelectorAll('.AddForm');
let myform = document.querySelectorAll('.MyForm');
let cloneform = myform.cloneNode(true);
addform.appendChild(cloneform);
}
createimg(event){
this.imgfile = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.imgfile);
reader.onload = () => {
this.img = reader.result;
};
}
sendform(event){
let name = document.querySelectorAll(".name");
let description = document.querySelectorAll(".description");
let formdata = new FormData;
//populate formdata with input values from the 'name' class
for (let i = 0; i < name.length; i++) {
let stringname = (name[i] as HTMLTextAreaElement).value;
formdata.append('name',stringname);
}
//populate formdata with input values from the 'description' class
for (let i = 0; i < description.length; i++) {
let stringdesc = (description[i] as HTMLTextAreaElement).value;
formdata.append('description',stringdesc );
}
//submit the form
}
I'm able to add more forms using the button, but when it comes to adding an image preview dynamically after selecting a file, I'm stuck. The functionality works only for the first form and not for the dynamically added ones. How can I fix this issue considering all data needs to be submitted together in one formdata request? Your help would be highly appreciated.