![](/img/trans.png)
[英]unable to call another method from [displayWith] in angular material autocomplete
[英]Binding 'this' in Angular Material Autocomplete displayWith using Angular 5
我試圖使用 Material Angular 自動完成功能,但我遇到了 displayWith 函數,該函數顯然可以用作選擇時顯示的輸出。 我想在顯示函數中調用一個自定義函數,例如
displayFn(id) {
return this.getValue(id)
}
getValue(id) {
/**return some string
}
對於自動完成
<mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of outletFilterOptions | async [value]="option.outletId">
{{ option.outletName }}
</mat-option>
</mat-autocomplete>
如您所見,我使用id
作為模型而不是整個對象。
當顯示函數返回 this.getValue 未定義的錯誤時,我在 Stack Overflow 上搜索了一個解決方案,並建議我使用[displayWith]="displayFn.bind(this)"
。
但不幸的是,這對我也不起作用。 我正在使用Angular 材料 5.1.0。
有什么我想念的嗎?
displayFn = value => {
// now you have access to 'this'
this.someMethod();
return 'formatted display';
}
您可以將模板更改為
<mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn(id, this)">
在模板內部, this
是對您的組件的引用。 然后只需將您的功能更改為
displayFn(id, _this) {
return _this.getValue(id)
}
如果[displayWith]
需要是一個函數,您可以創建一個屬性來返回您的displayFn
如下所示:
get createDisplayFn() {
return (id) => {
return this.getValue(id)
}
}
並將您的綁定更改為[displayWith]="createDisplayFn"
。 由於 ES6 箭頭函數無法重新綁定, this
仍然應該是對您的組件的引用。
將cThis = this
定義為類的屬性,然后在displayFn
函數中使用它:
<mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn(id, cThis)">
cThis = this;
displayFn(id, cThis) {
return cThis.getValue(id)
}
getValue(id) {
/**return some string
}
演示昭示着在結合displayWith
在使用屬性之前,您只是錯過了undefined
檢查。
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="optionSelected($event)">
<mat-option *ngFor="let user of users" [value]="user" >
{{ user.first_name }} {{ user.last_name }}
</mat-option>
displayFn(user) {
if (!user) return '';
return user.name;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.