使用Angular 5在Angular Material Autocomplete display中绑定'this'

问题描述 投票:2回答:4

我试图使用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。

有什么我想念的吗?

javascript angular angular-material angular-material2 angular-material-5
4个回答
4
投票
displayFn = value => {
  // now you have access to 'this' 
  this.someMethod();
  return 'formatted display';
}

3
投票

您可以将模板更改为

<mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn(id, this)">

模板内部this是对Component的引用。然后只需将您的功能更改为

displayFn(id, _this) {
  return _this.getValue(id)
}

如果[displayWith]需要是一个函数,你可以创建一个返回你的displayFn的属性,如下所示:

get createDisplayFn() {
  return (id) => {
    return this.getValue(id)
  }
}

并改变你对[displayWith]="createDisplayFn"的绑定。由于ES6箭头功能无法重新绑定,因此this应该仍然是对组件的引用。


0
投票

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
}

Demo显示在displayWith绑定


0
投票

您在使用属性之前错过了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;
}   
© www.soinside.com 2019 - 2024. All rights reserved.