Material.Angular.io mat-autocomplete [displayWith]函数更新范围变量 [英] Material.Angular.io mat-autocomplete [displayWith] function update scope variables

查看:80
本文介绍了Material.Angular.io mat-autocomplete [displayWith]函数更新范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我可以在实例化mat-autocomplete的组件控制器中访问本地声明的变量.我面临的问题是局部变量卡在此范围内,我无法更新它们.

I'm running into an issue where I can access locally declared variables in the component controller instantiating the mat-autocomplete. The problem I'm facing is the local variables are stuck in this scope and I can't update them.

最终,我正在将显示字符串和绑定到输入模型的变量连接起来.这给了我一个自动完成输入,为用户添加了帮助者文本,理想情况下,该文本是最新的,并且清除了输入.文本目前正在不断串联,很快就创建了不可用的文本

Ultimately what I'm doing is concatenating the display string and a variable bound to the input model. This is giving me an autocomplete input that adds helper text for the user, ideally the text is up to date with clearing the input. The text is currently continuously concatenating, creating unusable text pretty quickly

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>

component.ts

component.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:未知方法绑定")第二个是使用箭头功能以保留上下文.像这样:

You have two options, the first one is just calling [displayWith]="displayFn.bind(this)" which looks awful but I can confirm that this works (although I got an Error on my WebStorm saying "ng: Unknow Method bind") And the second one is to use an arrow function in order to preserve the context. Something like this:

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>

这篇关于Material.Angular.io mat-autocomplete [displayWith]函数更新范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆