【问题标题】:angular unable to set value to form control角度无法设置值以形成控制
【发布时间】:2018-05-07 07:31:48
【问题描述】:

基本上我正在尝试编辑和更新我在数据库中的现有数据。 因此,首先根据需要,我从数据库中获取特定员工的数据并将其设置为我的 EMPLOYEE 属性,如下所示 --,

这是我从数据库获取数据后保存数据的类属性。

  employee: any; //This is where the employee saved after getting from DB

此方法正在从数据库中获取数据并成功。

getEmployee(id){
    var url = `http://localhost:3000/employee/get/${id}`;    
    this.crudService.getItem(url).subscribe((data:any)=>{
      this.employee = data.data;     
    })
  }

之后,我想使用并将值设置为我的表单输入之一,作为类属性 EMPLOYEE 的默认值。我在 FORM CONTROL 中像这样(如下)使用它,但不起作用--,

this.employeeName = new FormControl(
      this.employee.employeeName, [Validators.required, Validators.minLength(5), Validators.maxLength(50)]
    );

但是当我通过 VALUE ATTRIBUTE 直接将它用于 html 时它可以工作,如下所示 --,

<input type="text" class="form-control form-control-sm" 
 id="inputEmployeeName" 
 name="employeeName" 
 formControlName="employeeName" 
 value="{{employee.employeeName}}"
 >

但我不想要这个。我想将值设置为 FORM CONTROL。 我怎样才能做到这一点 ?

【问题讨论】:

    标签: angular form-control


    【解决方案1】:

    试试下面的代码

    this.myFormGroup.setValue({
      formControlName1: myValue1, 
      formControlName2: myValue2
    });
    

    【讨论】:

    • 显示错误:Cannot read property 'employeeName' of undefined
    • 我是这样使用的:this.editEmployeeForm.setValue({ employeeName: this.employee.employeeName });
    • 你能创建 plunker 或 stackblitz 吗,我可以在哪里看到你的代码来找出你哪里出错了。
    • @SushilMandi 请检查 getEmployee(id) 的响应,并在设置值上方添加 if 条件。这里可能是异步导致的问题,在将结果输入到 setValue 中的 this.employee 之前被触发,因此您收到员工未定义的错误。
    • 我可以在 stackblitz 中创建 MEAN 应用吗?
    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2017-10-28
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多