如何基于数组长度创建动态表格?

时间:2019-06-03 10:14:33

标签: angular

我尝试过这样,它是根据附件(数组)长度生成表单的。

但是问题是当我在用户名/密码字段中输入值时,它正在下一行复制。

enter image description here

jest.mock(....)

在组件中:

    <form [formGroup]="form" >

        <button type="submit" (click)="submit()">Submit</button>

        <div *ngFor="let d of attachmentAr;"> 
          <div formArrayName="items" 
          *ngFor="let creds of form.controls.items?.value;
           let i = index">
            <ng-container [formGroupName]="i">
            <br>
              <input placeholder="name" formControlName="attachment" value="{{d.name}}">
              <input placeholder="Username" formControlName="username">
              <input placeholder="Password" formControlName="password">
            </ng-container>
          </div>
        </div>
         <br>
        <textarea type="input" formControlName="remark"></textarea>

    </form>

如何防止在下一行中重复该值。并最终在提交时收集所有行数据。

2 个答案:

答案 0 :(得分:1)

将您的addCreds()方法更改为此:

addCreds() {
  const formArray = this.form.controls.items as FormArray;
  this.attachmentAr.forEach((item) => {
    formArray.push(this.fb.group({
        attachment: item.name,
        username: '',
        password: '',
      }));
  })

}

以html

<form [formGroup]="form">

    <button type="submit" (click)="submit()">Submit</button>


    <div formArrayName="items"
         *ngFor="let creds of form.get('items')?.controls;
       let i = index">
        <ng-container [formGroupName]="i">
            <br>
            <input placeholder="name" formControlName="attachment">
            <input placeholder="Username" formControlName="username">
            <input placeholder="Password" formControlName="password">
        </ng-container>
    </div>

    <br>
    <textarea type="input" formControlName="remark"></textarea>

</form>

答案 1 :(得分:0)

不要使用.value而是使用.controls

<form [formGroup]="form">
    <button type="submit" (click)="submit()">Submit</button>

    <div *ngFor="let d of attachmentAr;"> 
      <div formArrayName="items" 
      *ngFor="let creds of form.get('items')?.controls; let i = index">
        <ng-container [formGroupName]="i">
        <br>
          <input placeholder="name" formControlName="attachment" value="{{d.name}}">
          <input placeholder="Username" formControlName="username">
          <input placeholder="Password" formControlName="password">
        </ng-container>
      </div>
     </div>
     <br>
    <textarea type="input" formControlName="remark"></textarea>

</form>