Javascript 单击后重复div元素

Javascript 单击后重复div元素,javascript,html,angular,forms,angular-material,Javascript,Html,Angular,Forms,Angular Material,我需要的是,当单击按钮(ADD)时,会生成一个由字段和删除按钮组成的表单。单击按钮时,应删除所有表单字段和删除按钮本身 <button type="button" class="btn btn-outline-success" (click)="AddBtn()"><span class="fa fa-plus"></span>Add</button> <div

我需要的是,当单击按钮(ADD)时,会生成一个由字段和删除按钮组成的表单。单击按钮时,应删除所有表单字段和删除按钮本身

<button type="button" class="btn btn-outline-success" (click)="AddBtn()"><span class="fa fa-plus"></span>Add</button>

<div *ngIf="isformes" >
  
<div>
  <form>
      <table>
          <div>
            
              <tr>
            
                  <td>
                      <mat-form-field ">
                          <mat-label>Name</mat-label>
                          <input matInput placeholder="Name"  autocomplete="off" required>
                      </mat-form-field>
                  </td>
               </tr>
          </div>
       </table>
   </form>
   <button type="button" class="btn btn-outline-success" (click)="DelBtn()"><span class="fa fa-plus"></span>Delete</button>
   </div>
添加

我建议创建一个新的表单组件,它将包含输入字段和删除按钮,然后在用户单击添加按钮时动态加载该组件

您需要使用componentFactoryResolver,它将返回componentFactory,您可以使用它动态创建组件,并使用ng模板将其添加到UI中

addForm = () => {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
      FormComponent
    );
    const component = this.container.createComponent(componentFactory);
    component.instance.removeForm.subscribe((x) => {
      this.removeForm();
    });
    this.components.push(component);
  };
要删除组件,请在formComponent中公开一个输出参数,当用户单击该父组件时,它将发出该事件,在这里,您可以使用以下代码从UI中删除该组件

 removeForm = () => {
    const component = this.components.find(
      (component) => component.instance instanceof FormComponent
    );
    const componentIndex = this.components.indexOf(component);

    if (componentIndex !== -1) {
      this.container.remove(this.container.indexOf(component));
      this.components.splice(componentIndex, 1);
    }
  };
以下是示例代码沙盒:-

使用
*ngFor
可以在数组上循环并在UI上显示内容 在TS文件中

isformes=true;
formsArray=[“”];
DelBtn=delIndex=>this.formsArray.splice(delIndex,1);
AddBtn=()=>this.formsArray.push(“”);
HTML文件



您不需要任何方法,只需使用ngif*指令和两个按钮中的第一个按钮ngif*=“变量”和第二个按钮ngif*=!变量”-表单的变量依赖是否提交,
DelBtn()的代码在哪里
?HTML很有用,但除非我们看到删除按钮的JS,否则无法修复删除按钮的问题。我相信您需要看看
*ngFor
指令,您只需循环一个数组,删除并添加元素,这将自动反映在UI@WalterWhite那件事我已经做过了但是每次点击按钮的时候我都想重复这些表格,我被卡在里面了part@OwenKelvin你能给我一个例子吗?这是一个很长的例子。你能给我一个很短的例子吗?这是一个不长的例子,这将满足你的要求和你的应用程序的可扩展性。你有一个特别的限制吗rms用户可以添加?如果不是,我建议你这样做。嘿,谢谢你的帮助。它起作用了。你能解释一下DelBtn()是如何工作的吗?你将一个索引传递给函数,并从数组中删除带有该索引的项,Angular将在数组项发生变化时重新呈现UI