不显示Material2自动完成的值 [英] Value not displaying for Material2 Autocomplete

查看:104
本文介绍了不显示Material2自动完成的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使自动完成功能显示对象的一个​​参数,但保存另一个参数,到目前为止,它似乎没有任何表现.

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

区别是[值]我要保存'option.Id'而不是'option'.

The difference is that [value] i want to save 'option.Id' and not '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

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-autocompletedisplayWithoptions进行过滤,以基于绑定到md-optionuser.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;
}

引用 朋克演示 .

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆