从角度材料的自动完成功能中获取“ id”选择的值

时间:2019-12-23 04:01:46

标签: angular

如何设置自动完成功能以获取所选的选项ID?

<mat-form-field>
    <input type="text" matInput 
        [formControl]="autocompleteControl" 
        [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let book of books" [value]="book.id"> <!-- THIS SHOW THE ID ON THE UI -->
                {{ book.title }}
            </mat-option>
        </mat-autocomplete>
</mat-form-field>

如果在 [value] 属性中将“ book.id” 更改为“ book.title” ,则用户界面会在自动完成输入,效果不好。我应该在哪里放置“ book.id” ,以便稍后在我的 component.ts 上问他?

1 个答案:

答案 0 :(得分:0)

您可以使用displayWith显示选项的特定值。

它需要一个映射函数,该函数将获取value中的mat-option并返回mat-option的显示值

尝试一下:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

/**
 * @title Simple autocomplete
 */
@Component({
  selector: 'autocomplete-simple-example',
  templateUrl: 'autocomplete-simple-example.html',
  styleUrls: ['autocomplete-simple-example.css'],
})
export class AutocompleteSimpleExample {
  myControl = new FormControl('1');
  options: string[] = ['One', 'Two', 'Three'];
  books: Array<{ id: string; title: string }> = [
    { id: '1', title: 'Book 1' },
    { id: '2', title: 'Book 2' },
    { id: '3', title: 'Book 3' },
    { id: '4', title: 'Book 4' },
  ];

  getTitle(bookId: string) {
    return this.books.find(book => book.id === bookId).title;
  }

  onSubmit() {
    console.log(this.myControl.value);
  }
}

在模板中:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input 
      type="text" 
      placeholder="Pick one" 
      aria-label="Number" 
      matInput 
      [formControl]="myControl" 
      [matAutocomplete]="auto">
    <mat-autocomplete 
      #auto="matAutocomplete"
      [displayWith]="getTitle.bind(this)">
      <mat-option 
        *ngFor="let book of books" 
        [value]="book.id">
        {{book.title}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
  <button (click)="onSubmit()">Submit</button>
</form>
  

这是您的推荐人Working Sample Demo Code