HTML-
<select (change)="selectRegion($event.target.value)" [ngClass]="{'error-control': !editForm.get('region').valid && editForm.get('region').touched}" id="region" type="text" placeholder="region" formControlName="region">
<option value="" disabled selected hidden>Region</option>
<option *ngFor="let region of regions" [value]="region.region_id"> {{region.region}}</option>
</select>
Ts-
*//called this details function in ngOnit()*
details() {
this.manageService.getDetails(this.doctorId)
.subscribe((res: any) => {
this.data = res.body.data;
this.editForm.patchValue({ region: this.data.user_profile.address.region });
this.cd.detectChanges();
});
}
*//Got the list of regions from this function.*
selectCountry(country: any): void {
if(country === 'Ethiopia') {
this.ethopiaSelected = true;
this.manageService.getRegion('ET')
.subscribe((resp: any) =>
this.regions = resp.body.data);
} else {
this.ethopiaSelected = false;
}
}
selectRegion(regionId): void {
this.selectedRegion = this.regions.filter((m) => m.region_id === parseInt(regionId)).map(x => x.region)[0];
this.manageService.getCityByRegion(regionId)
.subscribe((res: any) => {
this.cities = res.body.data;
});
}
我希望字段的开头是我从details()获得的值。 然后,如果用户想要更改它,则可以从下拉列表中选择它。 但是patchValue不起作用,也尝试了setValue。 有人可以帮忙吗?
答案 0 :(得分:0)
您可以使用 formControl 设置值:
editForm.get('region').setValue(value)
或者您可以简单地使用setValue 属性绑定
//template
<select [(ngModel)]="name">
//ts
name : any = value
答案 1 :(得分:0)
仅当我们从选项列表中设置选项的引用时,我们才能动态更改HTML Select的值。
在这里,您已在editform.patchValue()方法中创建了新对象。要解决此问题,首先您必须从区域列表中找到特定区域的参考,然后将其打补丁到所选区域。使用以下步骤-
检查区域列表是否在编辑表单中包含数据。如果有的话
使用
从区域列表中查找特定区域 const regionRef = this.regions.find(ele=>ele.region_id===this.data.user_profile.address.region.region_id)
并使用-
将该值修补到特定控件 this.editForm.controls.region.patchValue(regionRef)
就是这样。