角度材料2自动完成异步

时间:2017-09-06 15:01:16

标签: angular angular-material2

我有角度4和角度材料2.我想使用自动完成。在第一个版本中,自动完成的角度材料支持不对称的工作。

https://material.angularjs.org/latest/api/directive/mdAutocomplete#asynchronous-results

一切都很棒,很舒服。 在第二个版本中,我试图找到一个指南,但没有找到任何内容。

Angular 2 materials, autocomplete with remote data

How to use correctly autocomplete component from Angular2 MaterialDesign?

不算数。他们转向onInit的服务。我在点击时需要它,就像在第一个版本中一样。怎么做?

1 个答案:

答案 0 :(得分:2)

我不确定你的意思"他们求助于onInit"?如果要对click事件进行调用,请将代码块移动到click事件上调用的函数。您在问题中列出的这些示例会因为此行onInit而拨打.startWith(null),因此用户可以在点击输入字段后立即查看数据。

以下是一个例子:

HTML:

<md-input-container>
    <input mdInput [mdAutocomplete]="auto"
           placeholder="Select Name"
           [formControl]="myCtrl" 
           (click)="getData()">
</md-input-container>
...
...
...

TS:

myCtrl: FormControl;

  filteredItems: any;

  items;

  constructor(private dataService: DataService) {
    this.myCtrl = new FormControl();
  }

  ngOnInit(){

  }

  getData(){
    this.dataService.fetchData()
      .subscribe(
        (data) => {
          this.items = data.customers;
          this.filteredItems = this.myCtrl.valueChanges
            .startWith(null)
            .map(i => i && i === 'object' ? i.name : i)
            .map(name => name ? this.filterItem(name) : this.items.slice());

        }
    );
  }

  filterItem(name) {
   return this.items.filter(item => new RegExp(`^${name}`, 'gi').test(item.name)); 
  }

Plunker demo

希望这有帮助!