Material2 自动完成的值不显示 [英] Value not displaying for Material2 Autocomplete
问题描述
我试图让自动完成功能显示对象的一个参数,但保存另一个参数,到目前为止它似乎没有表现.
I am trying to get the autocomplete to display one parameter of object but save another and so far it doesn't seem to be behaving.
代码根据 Material2 自动完成站点:自动完成
Code is as per Material2 Autocomplete site: Autocomplete
区别在于 [value] 我想保存 'option.Id' 而不是 'option'.
The difference is that [value] i want to save 'option.Id' and not 'option'.
错误在于,当它记录 option.Id 时,它实际上并未在输入字段中显示值(将其留空).
The error is that while it records the option.Id it doesn't actually display the value in input field (leaves it blank).
my-comp.html
my-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>
my-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;
}
推荐答案
您可以使用 md-autocomplete
的 displayWith
从 options
中过滤根据绑定到md-option
的user.id
来查找user.name
,这里你需要使用bind(this)
以访问组件的数据.
you can filter from options
by using displayWith
of md-autocomplete
to find user.name
based on user.id
which is binded to md-option
, here you need to use bind(this)
in order to access data of component.
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn.bind(this)">
并在 displayFn
函数处做过滤
displayFn(id: number): string {
if (!id) return '';
let index = this.options.findIndex(option => option.id === id);
return index === -1 ? '' : this.options[index].name;
}
参考 plunker 演示.
refer plunker demo.
注释:在您的模板中,您使用的是 Id
,但在您的 User
类中,它是 id
.我认为这也可能导致设置为空白,如果您更正此错字,user.id
将设置为 md-input
.
Comment: in your template you are using Id
but in your User
class it's id
. I think this may also cause blank to be set and if you correct this typo, user.id
will be setted to md-input
.
这篇关于Material2 自动完成的值不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!