我试图让自动完成显示对象的一个参数但保存另一个参数,到目前为止它似乎没有表现。
代码根据 Material2 Autocomplete 站点:Autocomplete
不同之处在于 [value] 我想保存 'option.Id' 而不是 'option'。
错误是,虽然它记录 option.Id 它实际上并没有在输入字段中显示值(将其留空)。
我的comp.html
<md-input-container>
<input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let option of filteredOptions | async" [value]="option.Id">
{{ option.name }}
</md-option>
</md-autocomplete>
我的comp.ts
class MyComp implements OnInit {
myControl = new FormControl();
options = [
new User('Mary', 1),
new User('Shelley', 2),
new User('Igor', 3)
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.startWith(null)
.map(user => user && typeof user === 'object' ? user.name : user)
.map(name => name ? this.filter(name) : this.options.slice());
}
filter(name: string): User[] {
return this.options.filter(option => new RegExp(`^${name}`, 'gi').test(option.name));
}
displayFn(user: User): string {
return user ? user.name : user;
}
}
class User {
name: string;
id: number;
constructor(name: string, id: number)
this.name = name;
this.id = id;
}