簡體   English   中英

Material.Angular.io mat-autocomplete [displayWith] function 更新 scope 變量

[英]Material.Angular.io mat-autocomplete [displayWith] function update scope variables

我遇到了一個問題,我可以訪問組件 controller 中本地聲明的變量來實例化 mat-autocomplete。 我面臨的問題是局部變量卡在這個 scope 中,我無法更新它們。

關於更新 mat-autocomplete scope 變量的任何想法或想法。

最后,我正在做的是連接顯示字符串和一個綁定到輸入 model 的變量。這為我提供了一個自動完成輸入,為用戶添加了幫助文本,理想情況下文本是最新的並清除了輸入。 文本目前正在連續連接,很快就會創建無法使用的文本

html

  <input
   [(ngModel)]="filter>

  mat-autocomplete
    #auto="matAutocomplete" 
    [displayWith]="displayFn">
    <mat-option
      *ngFor="let option of filteredOptions | async"
      [value]="option">
      {{ option }}
    </mat-option>
  </mat-autocomplete>

組件.ts

  displayFn(search): string | undefined {
    if(!search) return; //check if the search isn't already populated
    if(!search.match(/(=|\*)/)){
      if(this.filter){
        this.filter += ' ' + search + '==*term*';
      }else{
        this.filter = search +'==*term*';

      }
      return this.filter; //this isn't persisting across the lifecycle
    }
  }

您有兩個選擇,第一個選擇只是調用[displayWith]="displayFn.bind(this)" ,這看起來很糟糕,但是我可以確認這是可行的(盡管我在WebStorm上看到一個錯誤,說“ ng:未知方法綁定” )第二個是使用箭頭功能以保留上下文。 像這樣:

displayFn(offer?: Offer): string | undefined {
    return offer && offer.name == this.currentOffer.name ? offer.name : undefined;
}

displayFnWrapper() {
   return (offer) => this.displayFn(offer);
}

並在模板中:

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFnWrapper()" (optionSelected)='assign($event.option.value)'>
    <mat-option *ngFor="let offer of filteredOffers$ | async" [value]="offer">{{ offer.name }}</mat-option>
</mat-autocomplete>

如果我使用示例 MyClass,其中

@Input() modeCity = false;

在 ngOnInit() 中,我可以訪問 modeCity 並更改它。 它反映在 class 中的其他方法。

在 HTML,

<mat-autocomplete #auto="matAutocomplete" autoActiveFirstOption [displayWith]="itemDisplayFn" (optionSelected)="selected($event)">

然后對於 ts 文件中的方法 itemDisplayFn(item: ..),modeCity 未定義。

我發現 itemDisplayFn() 方法以某種方式具有 static 上下文。 因此我創建了屬性,

static staticModeCity = false;

staticModeCity 可以像這樣在 ngOnInit() 中設置,

MyClass.staticModeCity = true

並像這樣在方法 itemDisplayFn() 中使用,

if(MyClass.staticModeCity)....

我不知道這是為什么。 當然 static 可能會發生沖突,如果在同一個父組件中多次使用同一個組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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