Angular 6:如何访问 mat-autocomplete 下拉列表中的所有选项值? [英] Angular 6: how to access ALL option values in mat-autocomplete dropdown?

查看:18
本文介绍了Angular 6:如何访问 mat-autocomplete 下拉列表中的所有选项值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于 Angular 文档中的示例 你可以在这里看到并在下面重复,我如何访问options中的其余对象数据?

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?

例如,如果对象不仅仅是键值格式的简单名称列表,而是更复杂的东西,例如来自 API 的数据:

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

文档中的示例太简单了,并没有告诉我如何让 name 显示在输入字段中,以及如何获取相应的 nameId在通过 API 返回 PUT 请求所需的 ts 文件中.

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:

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);
  }
}

推荐答案

我认为您正在寻找 onSelectionChange 选项:

I think you're looking for the onSelectionChange option:

您可以简单地添加到 mat-option:

You can simple add, to the mat-option:

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

每当您选择一个值时,都会触发.

Everytime when you select a value this will be triggered.

这篇关于Angular 6:如何访问 mat-autocomplete 下拉列表中的所有选项值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆