网站搜索

angular - 重置动态添加的字段值


我的组件有两个字段,分别叫做 employee(下拉菜单)和 EmployeeId,我正在像下图所示一样动态添加这两个字段的值:

当我选择特定的员工(例如 Employee2)进行编辑时,我将获取该员工(Employee2)的值并返回到输入字段,如下所示:

我在这里面临两个问题:

  • 当我更改选定的员工(前员工2)值时,它会在点击添加按钮之前就显示出来:

它应该只在点击添加按钮后显示

  • 当用户错误地选择了特定的员工进行编辑,但他不想编辑该员工时,那么在点击清除按钮时,所选的员工(例如员工2)必须从输入字段中移除。我尝试从输入字段中移除该员工,但我连同其他详细信息一起被移除了,像这样:

它应该这样删除:

Stackblitz 演示

答案#1

你可以尝试这段代码:

  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]};
  }