15

我试图使用 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 上搜索了解决方案,并建议我使用类似 .getValue 的方法[displayWith]="displayFn.bind(this)"

但不幸的是,这对我也不起作用。我正在使用Angular 材料 5.1.0。

有什么我想念的吗?

4

5 回答 5

28
displayFn = value => {
  // now you have access to 'this' 
  this.someMethod();
  return 'formatted display';
}
于 2019-04-23T18:41:50.447 回答
7

这是因为 this 没有绑定到组件及其绑定到 mat-select 选项

在此处输入图像描述在此处输入图像描述

现在要使用组件的功能,您必须使用箭头功能,最好的方法或从 HTML 函数传递 this

我将使用箭头函数来使用组件的功能

无箭头功能

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

带箭头功能

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

这适用于我的场景,它也适用于您的场景。

于 2020-01-31T14:57:10.083 回答
4

您可以将模板更改为

<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因此仍然应该是对您的组件的引用。

于 2018-04-20T10:30:29.310 回答
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
}

显示绑定的演示displayWith

于 2018-04-20T10:22:49.083 回答
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;
}   
于 2018-06-04T08:48:35.847 回答