簡體   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