md-autocomplete angular2从服务器获取数据显示焦点上的空下拉列表(但在第一次输入时填充)

时间:2017-08-02 14:16:13

标签: angular dropdown md-autocomplete

我从Angular2服务获取数据并尝试输入自动完成组件。当用户关注自动完成组件时,下拉列表将打开,但当用户键入内容时,下拉列表会显示结果。

我希望在自动完成功能集中时显示所有数据,而不仅仅是在首次输入后。

我的模板是:

<md-input-container>
    <input mdInput [mdAutocomplete]="auto" [formControl]="myCtrl">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete">
    <md-option *ngFor="let item of filteredItems | async" [value] = "item.name">
        {{item.name}}
    </md-option>
</md-autocomplete>

我的组件是:

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';

import {MyService} from '../services/my.service';

import {ItemInterface} from '../model/item-interface';

@Component({
   selector: 'app-test',
   templateUrl: './test.component.html',
   styleUrls: ['./test.component.css']
 })
 export class TestComponent implements OnInit {

 myCtrl: FormControl;
 filteredItems: Observable<ItemInterface[]>;

 items: ItemInterface[] = [];
 errorMessage:any = '';

 constructor(private myService: MyService) {

   this.myCtrl = new FormControl();
   this.filteredItems = this.myCtrl.valueChanges
                                    .startWith(null)
                                    .map(i => i && i === 'object' ? i.name : i)
                                    .map(name => name ? this.filterItem(name) : this.items.slice());

  }

  ngOnInit() {
    this.myService.getItems()
                    .subscribe(
                      items => this.items = items,
                     error => this.errorMessage = error
                  );
 }


 filterItems(name: string) {
   return this.items.filter(option => new RegExp(`^${name}`, 
'gi').test(option.name));
 }
} 

1 个答案:

答案 0 :(得分:1)

我认为如果你在回调中移动myCtrl代码,那应该可以解决问题。

我使用此plunker中的一些示例代码对其进行了测试,并且它正在运行。

TS:

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

ngOnInit(){
  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());

    }
);