Angular 5,带有动态嵌套数组的表单构建器

时间:2017-12-01 18:20:06

标签: angular typescript angular4-forms angular2-formbuilder

我有一个下一格式的表单:

this.setRotation(-90); // 'this' is your view.

属性数组是动态的,值始终取决于所选事件。此数组可以包含至少3个值和最多50个值。每个活动都有一个唯一的名称。这就是我在下一个方式选择事件后填充此数组的原因:

  this.form = this.formBuilder.group({
      title: new FormControl('', [Validators.required, Validators.maxLength(25)]),
      description: new FormControl('', [Validators.maxLength(45)]),
      event: new FormControl('', [Validators.required]),
      properties: this.formBuilder.array([])
    });

控制台向我展示了具有正确嵌套属性数组的相应表单对象:

 getValuesOfPoperty = function (prop) {
    this.selectedEventProperties = [];
    this.propertyService.getValuesOfPoperty(prop.propertyId)
      .subscribe(res => {
        this.selectedEventProperties.push({
          required: prop.required,
          name: prop.name,
          value: prop.defaultValue,
          type: res.name,
          items: res.items
        });
      })

  };

createItem(prop): FormGroup {
    return this.formBuilder.group({
      [prop.name]: prop.value
    });
  }

selectedEvent(type) {
   const temp = this.form.get('properties') as FormArray;

   type.properties.forEach(item => {
     temp.push(this.createItem(item));
     this.getValuesOfPoperty(item)
   });

   console.log(this.form.value)
 }

但与此同时,我在控制台中收到有关每个嵌套对象的错误:

  

找不到路径控件:'属性 - >日期'

     

找不到路径控件:'属性 - >登录'

     

找不到路径控件:'属性 - >结果'

这是我的HTML

{
 title: '',
 description: '',
 event: 'auth',
 properties: [{ Date: null},
              { Login: null},
              { Result: null}]
}

我很感激,如果有人能帮助我弄清楚我的错误在哪里,或者可以告诉我我做错了什么

提前致谢。

1 个答案:

答案 0 :(得分:1)

所以问题是在创建动态数组时显示选定的事件属性,导致我使用了服务,在收到实际数据之前呈现的html,这就是我如何解决这个问题

 getValuesOfPoperty = function (prop, temp) {
    this.selectedEventProperties = [];
    this.propertyService.getValuesOfPoperty(prop.propertyId)
      .subscribe(res => {
        // add property to dynamic array when the data has been received
        temp.push(this.createItem(prop));
        // work with an array for event properties
        this.selectedEventProperties.push({
          required: prop.required,
          name: prop.name,
          value: prop.defaultValue,
          type: res.name,
          items: res.items
        });
      })

  };

createItem(prop): FormGroup {
    return this.formBuilder.group({
      [prop.name]: prop.value
    });
  }

selectedEvent(type) {
   const temp = this.form.get('properties') as FormArray;

   type.properties.forEach(item => {
     this.getValuesOfPoperty(item, temp)
   });

   console.log(this.form.value)
 }