【发布时间】:2021-06-23 12:36:28
【问题描述】:
尝试使用可以按用户名或用户 ID 过滤的 Material 自动完成功能创建搜索。我在this Stackblitz 有一些工作。
如果您在自动完成选项中单击用户名,您将按预期进入用户详细信息页面。但是,如果您使用键盘箭头选择并使用“Enter”提交,它会在输入中显示 [object Object] 而不是名称。我将如何去显示用户名?
另外,如果用户输入数值,自动完成是否有办法列出 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]);
}
}
【问题讨论】:
-
等用户使用向上/向下箭头选择的值,你想显示文本而不是 [object Object]?喜欢
Barri Lebbon
标签: angular typescript autocomplete angular-material