如何获取数据部分并避免angular2中的空部分

时间:2018-05-30 08:26:14

标签: angular angular-reactive-forms

我有一个部分,数据即将到来,因为我已经提供了静态数据。 但随着静态数据,我也得到了空白部分。 所以,任何人都可以帮我获取数据并避免空位。

TS:

this.Emergencies = [{ 
  "ContactName": "Person1", 
  "Phone": "12345678", 
  "Relationship": "1" 
  "ContactName": "Person2", 
  "Phone": "37438367", 
  "Relationship": "4" 
  }]
this.emergencyContactForm = this._fb.group({
  itemRows: this._fb.array([this.createEmergency()])
});
this.Emergencies.forEach( 
  emergency => { 
  const control = <FormArray>this.emergencyContactForm.get('itemRows')['controls']; 
  control.push(this.createEmergency()); 
  }) 
  console.log(this.emergencyContactForm.get('itemRows')['controls'])
  for (let entry in this.Emergencies) { 
    this.emergencyContactForm.get('itemRows')['controls'][entry].patchValue({ 
    ContactName: this.Emergencies[entry].ContactName, 
    Phone: this.Emergencies[entry].Phone, 
    Relationship: this.Emergencies[entry].Relationship, 
    })
  }  }, 
  }

并且,我希望显示空部分,如果数据不存在,那么数据就在那里只有数据必须来

1 个答案:

答案 0 :(得分:1)

由于您对所有control.push(this.createItem());使用emergencies,因此创建[this.createEmergency()]

时无需使用control

你有:

this.Emergencies.forEach(
emergency => {
  const control = <FormArray>this.emergencyContactForm.get('itemRows')['controls'];
  control.push(this.createItem());
})

更改,

this.emergencyContactForm = this._fb.group({ 
    itemRows: this._fb.array([this.createEmergency()]) 
});

要,

this.emergencyContactForm = this._fb.group({ 
    itemRows: this._fb.array() 
});

所以,现在你不会得到额外的formControl

更新

if(this.Emergencies.length == 0){
  const control = <FormArray>this.emergencyContactForm.get('itemRows')
  ['controls'];
      control.push(this.createItem());
}