如何显示 GroupList 的 FormArray?

2024-05-14

我正在尝试制作一个交互式表单,在每一行上列出一个项目以及一个删除按钮(在我的示例中称为 verwijderen)。这些项目是从数据库中检索的,并且每个项目都实例化为名为的自定义对象LaborPeriod.

然后这些对象被转化为FormGroup对象,然后添加到FormArray。该表单组的定义如下:

  let formGroup = this.fb.group({
    id: this.account.laborperiods[i].id,
    beginDate: this.account.laborperiods[i].beginDate,
    endDate: this.account.laborperiods[i].endDate,
    hours: this.account.laborperiods[i].hours,
    account: this.account.laborperiods[i].account
  })
  if(!this.laborPeriodArray){
    this.laborPeriodArray = new FormArray([])
  }
  this.laborPeriodArray.push(formGroup)
}

主FormGroup中的laborPeriodArray的定义也是laborPeriodArray。主 FormGroup 如下所示:

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

整个组件如下所示: 在这里您可以看到 labourPeriodArray 在 onInit 方法中被初始化。

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private router: Router,
              private accountService: AccountService) {
    this.title = "Account aanpassen";
    //console.log(this.account.enabled + " : " + this.account.role)
    this.accountUpdateForm = this.fb.group({
      name: [''],
      username: ['', [Validators.required, Validators.email]],
      status: '',
      permission:'',
      laborPeriodArray:this.fb.array([])
    });
  }

  ngOnInit(): void {
    let formGroupArray: FormGroup[] = [];
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          if(!this.laborPeriodArray){
            this.laborPeriodArray = new FormArray([])
          }
          this.laborPeriodArray.push(formGroup)
        }
        console.log("laborPeriod" + JSON.stringify(this.laborPeriodArray.length))

        this.ngOnChanges();
      });
  }

  ngOnChanges(): void {
    if (this.account !== undefined) {
      this.accountUpdateForm.reset({
        name: this.account.name,
        username: this.account.username,
        status: this.account.enabled,
        permission: this.account.admin,
        laborPeriodArray: this.laborPeriodArray
      });
    }
  }

所有 FormGroup 项目均已添加但未显示。行是空白的。这是我的 HTML 页面中的相关片段

<table class="table table-hover">
      <thead>
      <tr>
        <th>Begin datum</th>
        <th>Eind datum</th>
        <th>Aantal uren</th>
        <th>Actie</th>
      </tr>
      </thead>
      <tbody>
      <tr formArrayName="laborPeriodArray" *ngFor = "let laborperiod of laborPeriodArray.controls; let i = index" [formGroupName]="i">
        <td formControlName="beginDate">{{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}</td>
        <td formControlName="endDate">{{laborperiod.value.get('endDate') | date:'yyyy-MM-dd'}}</td>
        <td formControlName="hours">{{laborperiod.value.get('hours')}}</td>
        <button type="button" class="btn btn-default">
          <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
          Verwijderen
        </button>
      </tr>

这给了我浏览器错误ERROR Error: Cannot find control with unspecified name attribute但我为每个 td 行指定 formControlName。所以我不明白是什么导致了错误。此外,我还想知道如何将“删除”按钮链接到每行对应的数据。我认为我必须使用索引 I 为此,但我不确定。

EDIT:

应用 AJT_82 的解决方案后,我仍然无法正常工作。这似乎与数据库检索数据本身有关。当我将 AJT_82 的示例帐户数组添加到我的 ngOnInit() 中时,如下所示:

  account1 = { laborperiods: [{ id: 1, hours:11 }, { id: 2, hours:22 }, { id: 3, hours:33 }] }

  ngOnInit(): void {
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.accountService.getAccount(params.get("id")))
      .subscribe(account => {
        this.account = account;
        for(let i=0; i < account.laborperiods.length; i++){
          let formGroup = this.fb.group({
            id: this.account1.laborperiods[i].id,
            beginDate: this.account.laborperiods[i].beginDate,
            endDate: this.account.laborperiods[i].endDate,
            hours: this.account1.laborperiods[i].hours,
            account: this.account.laborperiods[i].account
          })
          this.laborPeriodArray.push(formGroup)
        }
        console.log(JSON.stringify(account.laborperiods[0].beginDate))
        this.ngOnChanges();
      });
  }

它可以工作,但只显示 3 行。这是示例帐户数组的总长度。

这是帐户类别:

export class Account {
  id: number;
  username: string;
  name: string;
  enabled: boolean
  password: string;
  person: Person;
  admin: boolean;
  laborperiods: LaborPeriod[]
  remainingLeaveHours:number;
}

这是 LaborPeriod 类:

export class LaborPeriod{
    id: number
    beginDate: Date
    endDate: Date
    hours: number
    account: Account
}

它的字段声明有什么问题吗?


你不能拥有formArrayName在与您的迭代相同的元素上并且formGroupName,你需要移动formArrayName到更高的水平。我也看到没有用formControlName,因为这些不是可编辑字段,Angular 会为此抛出错误。还可以使用例如...

{{laborperiod.value.get('beginDate') | date:'yyyy-MM-dd'}}

是不正确的,应该只是

{{laborperiod.value.beginDate | date:'yyyy-MM-dd'}}

假设在您的代码中,变量laberPeriodArray被宣布...

this.laborPeriodArray = 
     this.accountUpdateForm.controls.laborPeriodArray as FormArray

既然你指的是this.laborPeriodArray在您的代码中,因此如下:

if(!this.laborPeriodArray){
  this.laborPeriodArray = new FormArray([])
}

是多余的,您已经在表单的构建中将其声明为空 FormArray。但这只是一个旁注:)

总而言之,您的模板应该如下所示:

<table formArrayName="laborPeriodArray" >
  <tr *ngFor="let laborperiod of laborPeriodArray.controls; 
      let i = index" [formGroupName]="i">
    <td>{{laborperiod.value.hours}}</td>
  </tr>
</table>

DEMO https://stackblitz.com/edit/angular-qhxw2w?file=app%2Fapp.component.ts

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何显示 GroupList 的 FormArray? 的相关文章

随机推荐