angular - Select 未更新 Angular 6 中的用户信息
问题描述
我们有一个用户编辑个人资料表单,在其中更改该用户的现有信息并单击更新。问题是简单的输入正在更新用户信息,但选择不更新。这是代码:
TS
private populateForm() {
const unusedFields = [
'_id',
'__v',
'username',
'email',
];
const userInfo = Object.assign({}, this.user);
unusedFields.forEach((field) => delete userInfo[field]);
this.SettingsForm.setValue(userInfo);
}
private buildSettingsForm() {
this.SettingsForm = this.fb.group({
country: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
firstName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
gender: [null, [Validators.required]],
jobTitle: [null, [Validators.required]],
lastName: [null, [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
description:[null, [Validators.required]],
});
this.SettingsForm.setValidators(this.minimumAge(18));
}
UpdateUser() {
this.usersService.EditUser(this.SettingsForm.value).subscribe(
data => {
this.router.navigate(['home']);
},
err => console.log(err)
);
}
HTML
<form action="" [formGroup]="SettingsForm" (ngSubmit)="UpdateUser()">
...
...
<div class="col-md-6">
<div class="form-group form-signup">
<input class="form-control form-control-lg" placeholder="lastName" type="text" id="lastName"
formControlName="lastName" />
<span *ngIf="!SettingsForm.get('lastName').valid && SettingsForm.get('lastName').touched"
class="help-block">Please enter a valid username!</span>
</div>
</div>
</div>
<div class="row">
<div class="form-group form-signup col-md-6">
<select class="form-control form-control-lg">
<option value="">{{user.country}}</option>
<option ngDefaultControl [ngValue]="country.name" *ngFor="let country of countries"
formControlName="country">{{country.name}}</option>
</select>
<span *ngIf="!SettingsForm.get('country').valid && SettingsForm.get('country').touched"
class="help-block">Please enter a country!</span>
</div>
...
...
</form>
如您所见,第二个是国家/地区的选择,无论您更改什么,它都不会在刷新页面后更新值,它会获得与以前相同的值。此问题仅在选择时发生。所以问题出在 Angular 方面而不是在后端,因为其他输入正在更新值。出了什么问题,我们该如何解决?
解决方案
设置formControlName="country"
为select
标签而不是option
.. 像这样更改代码,
<select class="form-control form-control-lg" formControlName="country">
<option value="">{{user.country}}</option>
<option ngDefaultControl [ngValue]="country.name" *ngFor="let country of countries">{{country.name}}</option>
</select>
推荐阅读
- python - 如何将 Bash 命令从 Python 传递到正在运行的 Docker 容器
- typescript - Babel - 打字稿预设
- groovy - 检查一些数字
- mongodb - 使用 $lookup 管道阶段的问题:性能问题和使用
- c# - 使用 Lambda 表达式检查字符串数组是否具有相同的字符串值
- c - 使用 OpenMP 并行化稀疏矩阵
- html - CSS: 'body' 和 'html' 设置为 'overflow-x: hidden;' 并且粘性导航栏有效,但页面右侧有额外的可滚动空白
- python - 使用 Python 从批处理文件中获取退出代码
- php - 错误:未指定应用程序加密密钥。但它存在
- laravel - Auth::user() - 属性或方法“{username}”未定义 [Vue, Laravel]