簡體   English   中英

如何對 Angular 中的兩個值使用一個 Material Autocomplete 輸入?

[英]How to use one Material Autocomplete input for two values in Angular?

嘗試使用可以按用戶名或用戶 ID 過濾的 Material 自動完成功能創建搜索。 我在這個 Stackblitz中有點工作。

如果您在自動完成選項中單擊用戶名,您將按預期進入用戶詳細信息頁面。 但是,如果您使用鍵盤箭頭指向 select 並使用“Enter”提交,則會在輸入中顯示 [object Object] 而不是名稱。 我將如何 go 關於顯示用戶名?

此外,如果用戶輸入數值,是否有辦法自動完成列出 ID 而不是名稱?

HTML:

<p>Search Users by Name or ID</p>
<form [formGroup]="searchForm" (ngSubmit)="onSubmit()">
  <input type="text" [matAutocomplete]="auto" [formControl]="searchControl" />
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option (click)="onSubmit()" *ngFor="let option of (filteredOptions | async)" [value]="option">
      {{ option.name }}
    </mat-option>
  </mat-autocomplete>
  <input type="submit" style="display: none;">
</form>

TS:

import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs";
import { map, startWith } from "rxjs/operators";
import { Router } from "@angular/router";
import { FormGroup, FormControl } from "@angular/forms";
import { User } from "../user";
import { UserService } from "../user.service";

@Component({
  selector: "app-users",
  templateUrl: "./users.component.html",
  styleUrls: ["./users.component.css"]
})
export class UsersComponent implements OnInit {
  filteredOptions: Observable<User[]>;
  users: User[] = [];
  options: User[];
  searchControl = new FormControl();
  searchForm = new FormGroup({
    searchControl: this.searchControl
  });

  getUsers(): void {
    this.users = this.UserService.getUsers();
  }

  constructor(public router: Router, private UserService: UserService) {}

  ngOnInit() {
    this.getUsers();

    this.options = this.users;

    this.filteredOptions = this.searchControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(value))
    );
  }

  private _filter(value: string): User[] {
    const filterValue = value;
    return this.options.filter(
      option =>
        String(option.id)
          .toLowerCase()
          .indexOf(filterValue) > -1 ||
        option.name.toLowerCase().indexOf(filterValue) > -1
    );
  }

  // Search bar
  onSubmit() {
    let userId = this.searchControl.value.id;
    this.router.navigate(["user-details", userId]);
  }
}

我認為您需要使用 AutoComplete 的displayWith屬性,因此所需的代碼更改是:

HTML:

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFunction">
    <mat-option (click)="onSubmit()" *ngFor="let option of (filteredOptions | async)" [value]="option">
      {{ option.name }}
    </mat-option>
</mat-autocomplete>

在 TS 中:

displayFunction(user: User): string {
    return user && user.name ? user.name : "";
}

StackBlitz_Demo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM