繁体   English   中英

使用ngModel指令和value属性更新表单

[英]Use ngModel directive and value attribute to Update a form

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

 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属性中获取的并返回空值。 如果是这样,这是我的推论,我不知道如何将value属性绑定到ngModel 是否有其他可行的方法来实现这一目标?

由于您使用的是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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM