文章内容

2021/6/3 14:20:57,作 者: 黄兵

mat-autocomplete 更新方式

在使用Angular Material的mat-autocomplete时,如果需要从后端读取数据,并且更新,具体操作如下:

<mat-form-field appearance="fill" class="col-lg-4">
<mat-label>ASN</mat-label>
<input matInput aria-label="State" [matAutocomplete]="auto" [formControl]="ASNFormControl" required>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChange($event)">
<mat-option *ngFor="let item of filteredStates | async" [value]="item.id">
{{item.ASN}}
</mat-option>
</mat-autocomplete>
</mat-form-field>

这里主要是与官方示例无异,具体可以参考这里:Autocomplete

增加了optionSelected事件,当更改选择值的时候触发,具体代码如下:

onSelectionChange($event): void {
this.ASNId = $event.option.value;
}

首先初始化mat-autocomplete的值:

ASNId: number;

由于mat-autocomplete在新增的时候保存的是Id,而在更新的时候是显示的具体值,具体截图如下:

在编辑的时候,获取的是id的名称:


所以我们需要在后台获取id的同时也要获取显示值,具体代码如下:

getIPRangeById(cloudIPRangeId: number) {
this.isLoading$.next(true);
this.sub = this.cloudService.getCloudIPRange(cloudIPRangeId).subscribe(res => {
this.ASNId = res.ASNId;
}, error => {
this.errorMessages.push({description: error.message});
}, () => {
this.getAllCountries();
this.getRegion(this.countryValue);
this.getCity(this.regionValue);
this.ASNFormControl.setValue(this.cloudIPRangeModel.ASN);
this.isLoading$.next(false);
});
}

这里在加载的时候将获取ASNId,如果没有更改,ASNId值不变,如果更改,将触发optionSelected事件,具体代码可以参考文章开头,这样就实现了mat-autocomplete值得更新,保存mat-autocomplete值代码如下:

editCloudIPRangeSave($event): void {
this.isSaveLoading = true;
this.cloudService.editCloudIPRange( this.ASNId).subscribe(res => {
if (res.returnResult === 'ok') {
this.router.navigate(['/management/sites/cloud/ips']);
}
});
}

这里保存的是ASNId值,并不是mat-autocomplete显示值。

在新增的时候,mat-autocomplete显示的是id值,但是在修改的时候mat-autocomplete显示的是名称值,但无论更新还是新增都保存的是id值。


参考资料:

1、Angular material auto complete change event not called when component loading?

2、Autocomplete


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - mat-autocomplete 更新方式

分享到:

发表评论

评论列表