重置动态添加的字段值

时间:2019-03-15 11:16:41

标签: angular typescript angular6

我的组件有2个字段,分别称为employee(下拉列表)和EmployeeId,我正在动态添加这2个字段值,如下图所示:

enter image description here

当我选择特定的Employee(ex Employee2)进行编辑时,我将把Employee(Employee2)的值返回到如下输入字段:

enter image description here

  

我在这里面临2个问题:

  • 当我更改选定的Employee(Ex Employee2)值时,它会在单击添加按钮之前反映出来:

enter image description here

仅在点击添加按钮后,该信息才会反映

  • 当用户错误地选择特定员工进行编辑但他不想编辑该员工时,则必须从中删除所选员工(前员工2)在单击Clear按钮的输入字段中,我尝试从i / p字段中删除Employe,但是我将其与类似的详细信息一起删除: enter image description here

应该这样删除:

enter image description here

Stackblitz DEMO

1 个答案:

答案 0 :(得分:2)

您可以尝试以下代码:

  addFieldValue() {
    if(this.newAttribute.employee && this.newAttribute.id){
      const index = this.fieldArray.findIndex((item) => this.newAttribute.employee === item.employee);
      if (index<0) {
        this.fieldArray.push(this.newAttribute)
      }else{
        this.fieldArray[index] = this.newAttribute
      }
    }

    this.newAttribute = {};
  }          

  editFieldValue(index) {
     this.newAttribute = {...this.fieldArray[index]};
  }

但是您不能推送2名employee_1

如果您要推多个同名员工,可以尝试:

  editedField:number;

  addFieldValue() {
    if(this.newAttribute.employee && this.newAttribute.id){
      if (this.editedField == undefined) {
        this.fieldArray.push(this.newAttribute)
      }else{
        this.fieldArray[this.editedField] = this.newAttribute;
        this.editedField = undefined;
      }
    }

    this.newAttribute = {};
  }          

  editFieldValue(index) {
     this.editedField = index;
     this.newAttribute = {...this.fieldArray[index]};
  }