代码之家  ›  专栏  ›  技术社区  ›  Bhrungarajni

如何在angular2中获取带数据的节并避免空节

  •  -2
  • Bhrungarajni  · 技术社区  · 8 年前

    我有一个部分,数据即将到来,因为我已经给出了静态数据。 但是除了静态数据,我也得到了空的部分。 所以,谁能帮我只取数据,避免空集合呢?

    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 回复  |  直到 8 年前
        1
  •  1
  •   Sravan    8 年前

    因为你在使用 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());
    }