【发布时间】:2020-12-05 03:46:26
【问题描述】:
我正在尝试创建一个 Angular 表单来编辑记录。用户从记录列表页面被带到此编辑表单。在加载表单时,想要将从 API 获取的记录填充到表单元素中。在 ngOnInit 生命周期方法中使用 patchValue 方法。
修补表单控制变量后,该 mat-select 元素的值具有一个被填充的 setValue。但是,在屏幕中,它没有被刷新。如果它是 Text Input 组件而不是 mat-select,那么同样的机制工作得非常好。
HTML 代码是这样的:
<form [formGroup]="propertyProfileDetailsForm" autocomplete="off" novalidate (ngSubmit)="savePropertyProfile(propertyProfileDetailsForm.value)" fxLayout="column wrap"
fxLayoutAlign="center center" fxLayoutGap="10px">
<mat-card-content>
<mat-form-field appearance="fill" class="add-gap">
<mat-label>Building Type</mat-label>
<mat-select formControlName="buildingType">
<mat-option value="1">Independent House</mat-option>
<mat-option value="2">Residential Apartment</mat-option>
<mat-option value="3">Independent Building</mat-option>
<mat-option value="4">Shared Commercial Building</mat-option>
</mat-select>
</mat-form-field>
...
...
</mat-card-content>
</form>
还有我的 component.ts 文件:
export class PropertyProfileDetailsComponent implements OnInit {
isUpdate:boolean = true;
propertyId:any;
propertyProfile:PropertyProfile;
propertyProfileDetailsForm:FormGroup = new FormGroup({
propertyProfileId: new FormControl(0),
buildingType: new FormControl(0),
buildingCondition: new FormControl(0),
buildingRenowatedIn: new FormControl(''),
});
constructor(
private repoService: RepositoryService,
private route: ActivatedRoute,
private errorService: ErrorHandlerService,
) { }
ngOnInit(): void {
this.propertyId = this.route.snapshot.paramMap.get(this.routeParameterName);
this.getPropertyProfileByPropertyId(this.propertyId);
this.repoService.profileEditEmitter.subscribe(() => {
this.getPropertyProfileByPropertyId(this.propertyId);
});
}
private getPropertyProfileByPropertyId(property_id:number) {
this.repoService.getData('pprofile/property/'+property_id)
.subscribe((res:any) => {
this.propertyProfile = res.response;
this.isUpdate = (res.response === null && res.code === '000') ? false : true;
this.patchFormData();
},
(error) => {
console.warn(error);
this.errorService.handleError(error);
});
}
private patchFormData(){
console.warn(this.propertyProfile)
if (null !== this.propertyProfile) {
console.log('coming here....!!!')
this.propertyProfileDetailsForm.patchValue({
propertyProfileId: this.propertyProfile.propertyProfileId,
buildingType: this.propertyProfile.buildingType,
buildingCondition: this.propertyProfile.buildingCondition,
buildingRenowatedIn: this.propertyProfile.buildingRenowatedIn,
});
console.warn(this.propertyProfileDetailsForm.get('buildingType').value);
// This console message is printing the value fetched from API, but it is not refreshing.
}
}
感谢任何帮助,我是 Angular 的新手并通过视频自学。请随意指点 如果我犯了一些愚蠢的错误,请退出。
【问题讨论】:
-
buildingType的值是多少?我的意思是确保它是string -
value="1" 表示它的值是一个字符串。如果是数字,请使用 [value]="1"