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));
}
}
非常感谢,Nehal。它根据你的解释工作。 – Fabrizio