[英]Angular mat-autocomplete doesn't work with options returned by function
I have took autocomplete example from Material official web site and changed getting options from variable of component class to function, options display but I can't select anything, clicking on drop-down doesn't select a value.
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of options()" [value]="option">
{{option.value}}
</mat-option>
</mat-autocomplete>
export class AutocompleteSimpleExample {
myControl = new FormControl();
options(): KeyValue[] {
return [{ key: "1", value: "One" }];
}
}
interface KeyValue {
key: string;
value: string;
}
由於 function 返回 ngFor 的數據源,點擊 mat-option 觸發變化檢測,導致 ngFor 獲取新數組並生成新 mat-option 導致選擇不起作用。 您可以通過使用 trackBy function 來防止這種情況
組件.html
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of options();trackBy:trackByIdentity" [value]="option">
{{option.value}}
</mat-option>
</mat-autocomplete>
<!-- #enddocregion mat-autocomplete -->
</mat-form-field>
組件.ts
trackByIdentity:TrackByFunction<{key:string,value:string}> = (index: number, item: any) => item.key;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.