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

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

有没有我遗漏的东西?

cThis = this 定义为 class 的 属性,然后在 displayFn 函数中使用它:

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


cThis = this;
displayFn(id, cThis) {
 return cThis.getValue(id)
}
getValue(id) {
 /**return some string
}

DemodisplayWith

中显示绑定

您可以将模板更改为

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

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

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

如果 [displayWith] 需要是一个函数,您可以创建一个 属性 来 returns 您的 displayFn 像这样:

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

并将绑定更改为 [displayWith]="createDisplayFn"。由于无法重新绑定 ES6 箭头函数,因此 this 仍应是对组件的引用。

您刚刚错过了使用属性前的 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;
}   
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):''
}

这在我的场景中有效,在你的场景中也有效。