使用Angular的matAutocomplete,如何显示对象的属性,但如何在其他地方引用对象本身?

时间:2019-12-06 20:00:16

标签: javascript angular mat-autocomplete

例如,我有标记:


<input type="text" class="form-control" placeholder="Project #" name="project" [(ngModel)]="key" (ngModelChange)="filterProjects(key);"  matInput [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="setProject($event.option.value)">
  <mat-option *ngFor="let project of filtered" [value]="project.ProjNum">
    {{project.ProjNum}}
  </mat-option>
</mat-autocomplete>

<div class="input-group-append">
  <button class="btn btn-info" (click)="load(selectedProject)">Load</button>
</div>

选择一个选项后,它将调用setProject()函数,该函数设置了稍后用于“我的加载”按钮的selectedProject。但是,由于当前起作用,将值绑定到[value]="project.ProjNum"将使用项目号调用setProject。将我的值设置为[value]="project"(这会将我的selectedProject设置为项目对象)似乎很直观,但是现在它将在我的输入字段中显示[object Object]

如何修改此设置,以便可以直接引用我的选项之外的project对象,而不仅仅是引用选定和显示的属性?

注意:我知道我可以使用ProjNum筛选项目列表以找到正确的项目,然后设置selectedProject,但我不想浪费资源循环当我已经有了想要的对象时,通过列表进行浏览。

1 个答案:

答案 0 :(得分:1)

您要使用displayWith函数。它允许您定义一个函数,该函数返回要在其中显示的值

来自docs

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option.name}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>



import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

export interface User {
  name: string;
}

/**
 * @title Display value autocomplete
 */
@Component({
  selector: 'autocomplete-display-example',
  templateUrl: 'autocomplete-display-example.html',
  styleUrls: ['autocomplete-display-example.css'],
})
export class AutocompleteDisplayExample implements OnInit {
  myControl = new FormControl();
  options: User[] = [
    {name: 'Mary'},
    {name: 'Shelley'},
    {name: 'Igor'}
  ];
  filteredOptions: Observable<User[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => typeof value === 'string' ? value : value.name),
        map(name => name ? this._filter(name) : this.options.slice())
      );
  }

  displayFn(user?: User): string | undefined {
    return user ? user.name : undefined;
  }

  private _filter(name: string): User[] {
    const filterValue = name.toLowerCase();

    return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
  }
}