Angular 6: how to access ALL option values in mat-autocomplete dropdown?

柔情痞子 提交于 2020-01-15 03:32:06

问题


Given the example in the Angular docs you can see here and also repeated below, how can I access the rest of the object data in options?

If for example, the object was more than just a simple list of names in key:value format, but something more complex such as data coming in from an API:

dataObject = {
  name: 'someName',
  nameID: 'someId',
  foo: 'bar'
  }

The example in the docs is too simple and isn't telling me how to get the name to display in the input field, and to also get the corresponding nameId in the ts file needed to return a PUT request via the API.

<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> 

component.ts:

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<string | User>(''),
        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);
  }
}

回答1:


I think you're looking for the onSelectionChange option:

You can simple add, to the mat-option:

(onSelectionChange)="setID(option.nameID)"

Everytime when you select a value this will be triggered.



来源:https://stackoverflow.com/questions/52362070/angular-6-how-to-access-all-option-values-in-mat-autocomplete-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!