【问题标题】:how submit dynamic forms如何提交动态表单
【发布时间】:2021-05-21 18:30:49
【问题描述】:

我有以下我无法解决的问题

是这种类型的一种形式

在 HTML 中

<button (click)="addform()">agregar formulario</button>
<div class="conten-form">
 <div class="MyForm">

  <label>Nombre</label>
  <input type="text" class="name">

  <label>descripcion</label>
  <input type="text" class="description">

  <label>Foto</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="enviar" (click)="enviarform()">
</div>

在 TS 中

img : any; //to show
imgfile : any; //to send it through the form
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;
 };
}

enviarform(event){
 let nombre = document.querySelectorAll(".name");
 let description = document.querySelectorAll(".description");
 let formdata = new FormData;

 //add all inputs class name
 for (let i = 0; i < nombre .length; i++) {
  let stringname = (nombre.[i] as HTMLTextAreaElement).value;
  formdata.append('name',stringname);
 }

 //add all inputs class description
 for (let i = 0; i < description.length; i++) {
  let stringdescription = (description.[i] as HTMLTextAreaElement).value;
  formdata.append('description',stringdescription );
 }
 //send the form
}

正如您将看到的,我可以使用添加按钮添加更多表单,克隆第一个表单,我已经解决了添加任意数量的文本输入部分,但在图像输入部分我不知道该怎么做,操作是在将图像附加到输入后,我会在 div.class= img 中获得我要附加的内容的预览图像,这使得它只能在第一种形式下工作,并且它不再适用于我动态添加的表单,因为它可以解决这个问题?考虑到我必须通过formdata一次发货,我提前谢谢你。

【问题讨论】:

    标签: javascript angular typescript angular6


    【解决方案1】:

    你不应该使用

     let addform = document.querySelectorAll('.AddForm');
     let myform = document.querySelectorAll('.MyForm');
     let cloneform = myform.cloneNode(true);
    

    完全没有。添加表格。相反,您应该为每个表单创建一个单独的组件。 查看我之前在 stackoverflow 上的 question 了解我的意思。

    更具体地检查答案stackblitz。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2019-01-09
      • 1970-01-01
      相关资源
      最近更新 更多