Mat-select:通过 promise 加载数据时没有预 selected 值
Mat-select: No preselected value when data loaded over the promise
我通过 http 为 mat-select 加载组数组。
我的 .ts 代码如下所示:
async ngOnInit(): Promise<void> {
this.groups = await this.service.loadGroups();
this.form = new FormGroup(
groupId: new FormControl(this.user.groupId || 0)
);
}
public get groupId(): AbstractControl { return this.from.get('groupId'); }
在我的 html 中:
<mat-form-field>
<mat-select formControlName="groupId" [value]="resellerGroupId.value" required>
<mat-option *ngFor="let group of groups" [value]="group.id">
{{ group.name }}
</mat-option>
</mat-select>
</mat-form-field>
所以当我像这样加载数据时,mat-select 中没有预selected 值。如果数据被硬编码为一个值数组——没问题,但是当我添加 Promise 时它就坏了。
我不明白为什么 ui 上的值在 loadGroups() 承诺得到解决后没有更新。
您需要使用带有 mat-option 的异步管道。查看 autocomplete example 了解它是如何完成的。
我通过 http 为 mat-select 加载组数组。 我的 .ts 代码如下所示:
async ngOnInit(): Promise<void> {
this.groups = await this.service.loadGroups();
this.form = new FormGroup(
groupId: new FormControl(this.user.groupId || 0)
);
}
public get groupId(): AbstractControl { return this.from.get('groupId'); }
在我的 html 中:
<mat-form-field>
<mat-select formControlName="groupId" [value]="resellerGroupId.value" required>
<mat-option *ngFor="let group of groups" [value]="group.id">
{{ group.name }}
</mat-option>
</mat-select>
</mat-form-field>
所以当我像这样加载数据时,mat-select 中没有预selected 值。如果数据被硬编码为一个值数组——没问题,但是当我添加 Promise 时它就坏了。 我不明白为什么 ui 上的值在 loadGroups() 承诺得到解决后没有更新。
您需要使用带有 mat-option 的异步管道。查看 autocomplete example 了解它是如何完成的。