我使用Angular 7和反应式表单创建“编辑配置文件”页面。 我从数据库中填写了所有输入值。例如,如果要更改名字和姓氏,请单击“更新”按钮,一切看起来都很好,所有字段都已更新。 问题是,如果我只想再次更新名字,则在单击“更新”按钮后,姓氏具有初始值。 因此,问题在于我的变量#f =“ ngForm”保留了旧值(第一个值),并且在更新过程之后,#f变量又有了第一个值。
<form [formGroup]="patientEditForm" #f="ngForm" (ngSubmit)="editPatientProfile(f)">
editPatientProfile(f: NgForm ) {
this.submitted = true;
this.isRequesting = true;
this.errors = '';
if (f.valid) {
this.userService.editPatientProfile(this.patientId,
this.patient.nin,
f.value.firstName,
f.value.lastName,
this.email,
f.value.password,
f.value.city,
f.value.country,
f.value.birthdate,
f.value.phoneNumber)
.finally(() => this.isRequesting = false)
.subscribe(
result => {
if (result) {
this.router.navigate(['/patient/account']);
localStorage.setItem('displayMessage1', "true");
window.location.reload();
}
},
errors => this.errors = errors);
}
}
<input type="email" value="{{patient.email}}" disabled class="form-control mb-2 mr-sm-2 mb-sm-0">
this.patientEditForm = this.formBuilder.group({
lastName: ['Test', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]],
firstName: ['Test', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]],
phoneNumber: ['0745119974', [Validators.required, Validators.pattern("[0-9]+")]],
birthdate: ['1996-02-10', [Validators.required,this.validateDOB.bind(this)]],
city: ['Iasi', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]],
password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(35), this.validatePasswordConfirmation.bind(this)]],
country: ['Romania', [Validators.required, Validators.minLength(3), Validators.maxLength(30), Validators.pattern("[a-zA-Z]+")]]
});
答案 0 :(得分:1)
最后,我通过在订阅事件中设置新属性来解决了这个问题:
private getPatient() {
this.userService.getPatient(this.patientId)
.subscribe((patient: PatientProfile) => {
this.patient = patient;
this.patientEditForm.controls['lastName'].setValue(patient.lastName);
this.patientEditForm.controls['firstName'].setValue(patient.firstName);
this.patientEditForm.controls['phoneNumber'].setValue(patient.phoneNumber);
this.patientEditForm.controls['birthdate'].setValue(patient.birthdate);
this.patientEditForm.controls['city'].setValue(patient.city);
this.patientEditForm.controls['country'].setValue(patient.country);
},
errors => this.errors = errors
);