【问题标题】:Angular 6: how to access ALL option values in mat-autocomplete dropdown?Angular 6:如何访问 mat-autocomplete 下拉列表中的所有选项值?
【发布时间】:2018-09-17 06:43:01
【问题描述】:

鉴于 Angular 文档 you can see here 中的示例并在下面重复,我如何访问 options 中的其余对象数据?

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

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

文档中的示例太简单了,并没有告诉我如何让name 显示在输入字段中,以及如何在返回 PUT 请求所需的 ts 文件中获取相应的nameId通过 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);
  }
}

【问题讨论】:

    标签: javascript angular angular-material angular6


    【解决方案1】:

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

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

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

    每次选择值时都会触发。

    【讨论】:

    • 我的话@Swoox!我想你可能已经做到了!谢谢!
    猜你喜欢
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多