2017-08-02 37 views
1

我从Angular2服务获取数据并尝试放入自动完成组件。当用户关注自动完成组件时,下拉列表将打开为空,但当用户键入内容时,下拉列表将显示结果。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

我认为,如果您将回调里面你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()); 

    } 
); 
+0

非常感谢,Nehal。它根据你的解释工作。 – Fabrizio

相关问题