文章内容
2021/6/4 15:43:55,作 者: 黄兵
mat-select默认选项在mat-dialog中不起作用的解决方案
最近在使用mat-dialog的时候,mat-select传值过去了,但是却无法将传过去的值默认选中,下面是代码:
addCity($event): void {
const dialogRef = this.dialog.open(IPCrawlerDialogComponent, {
width: '50vw',
data: {state: 'addCity', project: 'location', countryId: this.countryId, regionId: this.currentRegionId}
});
this.sub = dialogRef.afterClosed().subscribe(result => {
if (!result) {
// 重新加载表格
this.getAllCountries();
this.getAllRegions(this.countryId);
}
});
}
这里主要是传过去countryId,regionId两个值,之后再mat-dialog页面代码:
ngOnInit() {
if (this.data.project === 'location') {
if (this.data.state === 'addCity') {
this.title = '新增城市';
this.getAllCountries();
}
}
}
这边接收值,并做相应的判断,之后显示:
<div class="form-group row">
<mat-form-field appearance="fill" class="col-lg-6">
<mat-label>国家</mat-label>
<mat-select (valueChange)="countryChange($event)" [(value)]="this.data.countryId" [formControl]="locationCountryFormControl" required>
<mat-option *ngFor="let item of countryModel" [value]="item.id">
{{item.countryNameEn}}
</mat-option>
</mat-select>
<mat-hint align="end">{{locationCountryFormControl.value?.length || 0}}/64</mat-hint>
<mat-error *ngIf="locationCountryFormControl.invalid">
<mat-icon>info</mat-icon>请选择国家
</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="col-lg-6">
<mat-label>城市</mat-label>
<mat-select (valueChange)="regionChange($event)" [(value)]="this.data.regionId" [formControl]="locationRegionFormControl" required>
<mat-option *ngFor="let item of regionModel" [value]="item.id">
{{item.regionNameEn}}
</mat-option>
</mat-select>
<mat-hint align="end">{{locationRegionFormControl.value?.length || 0}}/64</mat-hint>
<mat-error *ngIf="locationRegionFormControl.invalid">
<mat-icon>info</mat-icon>请选择地区
</mat-error>
</mat-form-field>
</div>
这里绑定刚才传过来的countryId,regionId,加载之后刚才传过来的值默认被选中,但是经过多次测试,mat-select默认值却无法被选中,值也传到mat-diaolog组件上了。
之后通过如下方式设置默认值,问题解决:
ngOnInit() {
if (this.data.project === 'location') {
if (this.data.state === 'addCity') {
this.title = '新增城市';
this.getAllCountries();
this.locationCountryFormControl.setValue(this.data.countryId);
this.locationRegionFormControl.setValue(this.data.regionId);
}
}
}
这里在页面初始化的时候设置值,却可以使mat-select选中默认值。
参考资料:
1、Set default option in mat-select
黄兵个人博客原创。
发表评论
评论列表
JustTes2020 on 回复 有用(0)
test
JustTes2020 on 回复 有用(9)
test
JustTes2020 on 回复 有用(0)
test