值或form.value未定义

时间:2019-07-01 16:34:27

标签: angular7

我正在尝试将角形的未定义值定义为空值,直到输入表单数据为止。我收到错误TypeError:无法读取未定义的属性“值”。我知道这是因为没有定义我的值,然后是空值。我在文件中定义了它们,但是我不确定为什么表单不选择链接它们。

我尝试了Stackoverflow,Youtube和Angular Documents的多个建议。

Associate.component.ts

constructor(private service: AssociateService) { }

  ngOnInit() { //put null check
    this.resetForm();


  }
  resetForm(form?: NgForm) {
    if(form != null)
      form.resetForm();
    this.service.formData = {
      EmployeeID: null,
      FirstName: '',
      MiddleName: '',
      LastName: '',
      EmployeeType: null,
      EmployeeStatus: null,
      EmployeeLevel: null,
      EmployeeRole: null,
      Proactive: false

    }
  }

  onSubmit(form: NgForm) {
    debugger;
    if (form.value.EmployeeID == null)
      this.insertRecord(form);
    else
      this.updateRecord(form)
  }

Assocaite.component.html


<form #form="ngForm" autocomplete="off">
    <div style="margin-left: 10px">
        <div class="form-group">
        <label>EMPLOYEEID</label>
        <input   name="EmployeeID" #EmployeeID=ngModel [(ngModel)]="service.formData.EmployeeID" class="form-control">
    </div>

我拥有所有其他formData的HTML其余部分。只是想尽可能地修剪代码。

我需要form.value.EmployeeID来提取this.service.formData的值。任何帮助或指导都将是惊人的。我已经坚持了两天了。

1 个答案:

答案 0 :(得分:0)

另一种方法可能是:

Step1-创建模型对象Employee.model.ts

export class employee{
 employeeID:number,
 name:string,
 lastName:string,
 ...
 ...
 ...
}

Step2:在component.ts中初始化

emp:Employee | undefined;
constructor(private service: AssociateService) {
this.emp= new Employee();
}
 onSubmit() {

if (form.valid && this.emp.EmployeeID == undefined)
  this.insertRecord(this.emp);
else
  this.updateRecord(this.emp)
}

Step3-查找模型绑定的HTML文件

<input   name="EmployeeID" #EmployeeID=ngModel 
        [(ngModel)]="emp.EmployeeID" class="form-control">