首页 > 解决方案 > 使用 ngModel 指令和 value 属性来更新表单

问题描述

我正在尝试在我的 MEAN 堆栈应用程序中编辑一些数据,并且我正在使用 Reactive Form。我正在使用ngModel两种方式数据绑定和 HTML 输入的value属性。当我使用value属性填充表单时,我成功地将所需数据从我的 API 获取到 Input 字段中,但是当我单击Submit Button时。表单返回空值,我的MongoDB中的所有字段都返回空值。这是我在提交时运行的方法。

 editPatient() {
 const patient = {
  first_name: this.first_name,
  last_name: this.last_name,
  DOB: this.DOB,
  email: this.email,
  address: this.address,
  city: this.city,
  province: this.province,
  postal_code: this.postal_code,
  phone: this.phone,
  department: this.department,
  doctor: this.doctor
}
this.patientService.updatePatient(this.ID, patient).subscribe((patient: any) => {
  console.log(patient);
})}

这是我的 HTML 的单个 div。我还有更多,但逻辑也是一样的

<div class="form-group" [ngClass]="{'is-invalid':formErrors.first_name}">
  <label>First Name</label>
  <input type="text" placeholder="First Name" [(ngModel)]="first_name" formControlName="first_name" class="form-control"
    (blur)="logValidationErrors()" value={{patient.first_name}} required>
  <span class="help-block" *ngIf="formErrors.first_name">
    {{formErrors.first_name}}
  </span>
</div>

到目前为止,我认为我的问题是,当我使用两种方式绑定时,它期望值用户在输入字段中输入,但它不会读取/考虑它从属性中获取的内容作为用户输入数据并返回空值。如果这是真的,这是我的推论,我不知道如何将value属性绑定到ngModel。是否有任何其他解决方法可以实现这一目标?

标签: angularmean-stackangular-reactive-forms

解决方案


由于您使用的是响应式表单方法,因此您应该只在模板上使用[formGroup], 和formControlName指令,而不是使用[(ngModel)].

然后,您可以使用获取表单的值this.yourFormName.value

在您的组件类中:

...

constructor(
  private fb: FormBuilder,
  private patientService: PatientService
) {}

ngOnInit() {
  ...
  this.patientEditForm = this.fb.group({
    first_name: [],
    last_name: [],
    DOB: [],
    email: [],
    address: [],
    city: [],
    province: [],
    postal_code: [],
    phone: [],
    department: [],
    doctor: []
  });
  ...
}

...

editPatient() {
  this.patientService.updatePatient(this.ID, this.patientEditForm.value)
    .subscribe((patient: any) => {
      console.log(patient);
    })
}

...

在您的模板中:

<form [formGroup]="patientEditForm" ...>
  ...
    <div class="form-group" [ngClass]="{'is-invalid':formErrors.first_name}">
        <label>First Name</label>
    <input type="text" placeholder="First Name" formControlName="first_name" class="form-control"
      (blur)="logValidationErrors()" value={{patient.first_name}} required>
    <span class="help-block" *ngIf="formErrors.first_name">
      {{formErrors.first_name}}
    </span>
  </div>
  ...
</form>

推荐阅读