簡體   English   中英

使用 Angular 5 在 Angular Material Autocomplete 顯示中綁定“this”

[英]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-select 選項

在此處輸入圖片說明 在此處輸入圖片說明

現在要使用組件的功能,您必須使用箭頭功能,首選方法或從 HTML 功能傳遞

我將使用箭頭函數來使用組件的功能

沒有箭頭功能

displayFn(data: any) {
    return data.Id?this.sometask(data):''
}

帶箭頭功能

displayFn = (data: any) => {
    return data.Id?this.sometask(data):''
}

這適用於我的場景,也適用於您的場景。

您可以將模板更改為

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM