Angular7、为formarray控件动态赋值

Angular 7, dynamically assigning values to formarray controls

在 angular 7 中,我试图制作具有一些初始值的可编辑表单。我创建了一个也有 formarray 的表单组。我正在尝试在 formarray 中为 formcontrols 动态分配值,但 formcontrol 值未显示在表单上。

这是我的 html,

<form [formGroup]="UserForm" (ngSubmit)="submit()" >
  <ng-container>
    <span>Group Name</span>
    <mat-form-field id="uName">
      <input matInput autocomplete="off" formControlName="GroupName">
    </mat-form-field>
  </ng-container>
  <br>
  <span>User Details</span>
  <br> 
  <div id="divUser"> 
      <table mat-table [dataSource]="UserData" class="mat-elevation-z8" formArrayName="UserRow">
          <ng-container matColumnDef="id">
              <th mat-header-cell *matHeaderCellDef> Id </th>
              <td mat-cell *matCellDef="let row; let index = index" [formGroupName]="index">
                  {{index + 1}}.
              </td>         
          </ng-container>

          <ng-container matColumnDef="username">
              <th mat-header-cell *matHeaderCellDef>Server Name</th>
              <td mat-cell *matCellDef="let row; let index = index" [formGroupName]="index">
                  <mat-form-field>
                    <input matInput formControlName="username" autocomplete="off">  // this is showing blank fields
                  </mat-form-field>  
              </td>         
          </ng-container>

          <tr mat-header-row *matHeaderRowDef="UserColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: UserColumns;"></tr>
      </table>   
  </div> 
  <button mat-raised-button type="submit" color="primary">Submit</button>
</form>

和组件代码,

export class AdmissionComponent implements OnInit {
  public UserForm: FormGroup;
  public UserData;
  public UserColumns = ['id','username']  

  constructor(private formservice: AdmissionService,private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.getservicedata('FIRST')
    this.UserForm = this.formBuilder.group({
      GroupName: new FormControl(),     
      UserRow: this.formBuilder.array([this.CreateUser()])      
    });
  }

  onsetValue(result): void { 
    this.UserForm.controls['GroupName'].setValue(result.data[0].GroupName) // This is working and showing on html.      

    for (var key in result.data[0].usersRow) {
      if (key != '0'){ this.fnUserAdd(); }      
      // this.UserForm.value.UserRow[key].username = result.data[0].usersRow.username; // this is not working.
      this.UserForm.value.UserRow[key].username = 'testing'; // this is not wroking either
        };

        console.log(this.UserForm.value) // BUT this is perfactly showing data after setting up the values.
    }

    fnUserAdd(){
        (this.UserForm.get('UserRow') as FormArray).push(this.CreateUser());
        return this.getUserData();
    }
    getUserData(){
      this.UserData = this.UserForm.get('UserRow').value;
    }
    CreateUser(): FormGroup {
        return this.formBuilder.group({
          username: '',
          userrole: '',      
          present:''
        })
    }
    getservicedata(UserId){    
        return this.admiserv.getDetails(UserId)
        .subscribe(
          result => {
            this.onsetValue(result)         
          });
    }
  submit(){
    console.log(this.UserForm.value)
  }
}

它在 html 上显示空白输入字段,当我输入一些值并单击提交时,它起作用并将值发送到函数但不在输入字段中显示初始值。

请建议如何解决此错误。

谢谢

始终使用 setValue - 或 pathValue- 为 FormControl、FormArray 或 FormGroup- 赋值。所以,我想你想写这样的东西

const array=this.UserForm.get('UserRow') as FormArray;
for (var row of result.data[0].usersRow) {
   array.push(this.CreateUser());
   array.at(array.length-1).setValue(row)
  //or array.at(array.length-1).setPathValue({username:'test'})
}

真的,我建议您将函数 CreateUser 更改为

CreateUser(data:any): FormGroup {
   data={username:'',userrole:'',present:'',...data}
   return this.formBuilder.group({
          username: data.username,
          userrole: data.userrole,      
          present:data.present
   })
}

所以你可以简单

const array=this.UserForm.get('UserRow') as FormArray;
for (var row of result.data[0].usersRow) {
   array.push(this.CreateUser(row));
  //or array.push(this.createUser({username:'test'})
}

如果您想创建一个空的 formGroup,请调用 as

this.CreateUser(null)

stackblitz