1

例如我有标记:


<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()函数,该功能设置了以后用于我的加载按钮的选定项目。但是,由于它当前起作用,将值绑定到[value]="project.ProjNum"将调用带有项目编号的 setProject。虽然将我的值设置为[value]="project"(这会将我selectedProject的值设置为项目对象)似乎很直观,但它现在将显示[object Object]在我的输入字段中。

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

注意:我知道我可以使用 ProjNum 过滤我的项目列表以找到正确的项目,然后设置 my selectedProject,但是当我已经拥有我想要的对象时,我宁愿不浪费资源循环浏览列表。

4

1 回答 1

1

您想使用该displayWith功能。它允许您定义一个函数,该函数返回要显示的值

文档

<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);
  }
}
于 2019-12-06T20:08:10.943 回答