如何显示GroupLists的FormArray?

时间:2017-11-16 11:11:59

标签: javascript angular

我正在尝试创建一个交互式表单,在每行上列出一个项目和一个删除按钮(在我的示例中称为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([])
    });
  }

整个组件如下所示:您可以在此处看到,在onInit方法中初始化了laborPeriodArray。

  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,但我不确定。

编辑:

在应用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
}

其字段声明有什么问题吗?

2 个答案:

答案 0 :(得分:2)

您的迭代和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

答案 1 :(得分:0)

尝试替换

laborperiod.value.get('beginDate')

通过

laborperiod.value['beginDate']

我还建议你将FormGroup变量作为Class属性而不是OnInit()。

我还建议使用ReactiveForms及其API FormControls。

  • 让我知道发生了什么