文章内容
2021/2/6 16:24:20,作 者: 黄兵
关于Angular 修改表单Select不自动更新问题
在Angular中修改表单,当结果从后端读取,mat-select无法自动更新,需要点击页面上的一个表单才会更新,一图胜千言:
具体代码如下:
ngOnInit() {
// GET URI ID
this.getCloudVendorID = this.activateRoute.snapshot.params['id'];
// get all countries
this.getAllCountries();
// get all cloud vendor by id
this.getCloudVendorByID(this.getCloudVendorID);
}
getAllCountries() {
this.sub = this.ipCrawlerService.getAllCountries().subscribe(res => {
this.CloudVendorCountries = res;
}, () => {
this.errorMessages.push({description: '服务器出现错误,请稍后再试!'});
});
}
getCloudVendorByID(CloudVendorId: number) {
this.isLoading$.next(true);
this.sub = this.cloudVendorService.getCloudVendorByID(CloudVendorId).subscribe(res => {
this.CloudVendorModel = res;
this.cloudVendorCountryValue = res.countryId;
}, () => {
this.errorMessages.push({description: '服务器出现错误,请稍后再试!'});
}, () => {
this.isLoading$.next(false);
});
}
这里首先根据ID加载需要修改的内容,之后再加载mat-select的全部内容,根据id来判断select显示内容。
存在问题的原因:
再第一次全部加载mat-select内容,没有变更检测,导致必须点击页面上的form才产生变更检测。
解决方案:
constructor(private cloudVendorService: CloudProviderService,
private ipCrawlerService: IPCrawlerService,
private changeDetectorRefs: ChangeDetectorRef,
private activateRoute: ActivatedRoute) {
}
ngOnInit() {
// GET URI ID
this.getCloudVendorID = this.activateRoute.snapshot.params['id'];
// get all countries
this.getAllCountries();
// get all cloud vendor by id
this.getCloudVendorByID(this.getCloudVendorID);
}
getAllCountries() {
this.sub = this.ipCrawlerService.getAllCountries().subscribe(res => {
this.CloudVendorCountries = res;
this.changeDetectorRefs.detectChanges();
}, () => {
this.errorMessages.push({description: '服务器出现错误,请稍后再试!'});
});
}
getCloudVendorByID(CloudVendorId: number) {
this.isLoading$.next(true);
this.sub = this.cloudVendorService.getCloudVendorByID(CloudVendorId).subscribe(res => {
this.CloudVendorModel = res;
this.cloudVendorCountryValue = res.countryId;
}, () => {
this.errorMessages.push({description: '服务器出现错误,请稍后再试!'});
}, () => {
this.isLoading$.next(false);
});
}
这里增加了变更检测:
this.changeDetectorRefs.detectChanges();
最后问题解决,看看效果:
黄兵个人博客原创。
评论列表