【问题标题】:Angular : How to check if some control exist in form or notAngular:如何检查表单中是否存在某些控件
【发布时间】:2018-12-08 09:23:05
【问题描述】:

下面是我从服务中获取响应的代码。我在这里得到了一份员工名单。

我需要根据服务的响应动态绑定表单控件,我的服务返回的字段(EmployeeId、Name、Department 等)比表单具有的控件多。表单控件中没有用到的如何跳过?

this._employeeService.getEmployeeById(this.employeeId).subscribe((res: Response) => {
  this.employeeForm.get('FileUploader').setValue(null);
  for (const field in res) {
    this.employeeForm.controls[field].setValue(res[field]);
  }
});

this.employeeForm = this._fb.group({
  EmployeeId: 0,
  Name: ''
});

【问题讨论】:

    标签: angular angular6 angular-forms angular-formbuilder


    【解决方案1】:

    虽然已经有一个公认的答案,但值得一提的是,确实有一种方法可用,以防万一它可能对那些真正想要一种具体方法来验证给定 FormControl 在 FormGroup 中是否存在的人有用:

    包含(控件名称:字符串):布尔值


    来源:https://angular.io/api/forms/FormGroup#contains

    【讨论】:

      【解决方案2】:

      您可以使用 FormGroup 类的 get 方法。在 getEmployeeById 回调中更改迭代器,如下所示:

      for (const field in res) {
        const formControl = this.employeeForm.get(field);
      
        if (formControl) {
           formControl.setValue(res[field]);
        }
      }
      

      来源:https://angular.io/api/forms/FormGroup

      【讨论】:

        【解决方案3】:

        您可以使用patchValue 设置值

        this.employeeForm.patchValue(res);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-08-22
          • 2011-10-13
          • 1970-01-01
          • 2011-10-11
          • 2018-08-04
          • 2022-01-18
          • 2021-02-02
          相关资源
          最近更新 更多