angular material 2 异步自动完成

angular material 2 autocomplete asynchronous

我有一个 angular 4 和一个 angular material 2。我想使用自动完成功能。在第一个版本中,自动完成的 angular material 支持非对称工作。

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 服务。我需要点击它,就像在第一个版本中一样。如何做到这一点?

我不知道你所说的 "They turn to the service for onInit" 是什么意思?如果要调用 click 事件,请将代码块移动到在 click 事件上调用的函数。您在问题中列出的那些示例,由于这一行 .startWith(null) 而调用 onInit,以便用户可以在单击输入字段后立即看到数据。

这是一个例子:

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

希望对您有所帮助!