问题
I'm using Angular 4 with Materials 2.
I have successfully created some autocomplete fields using an array of data. Here my controller:
sectorCtrl;
allSectors
filteredSectors: any;
constructor() {
this.sectorCtrl = new FormControl();
this.filteredSectors = this.sectorCtrl.valueChanges
.startWith(null)
.map(name => this.filterValues(name));
}
filterValues(val: string) {
return val ? this.allSectors.filter(s => new RegExp(`^${val}`, 'gi').test(s.label)) : this.allSectors;
}
And my template:
<md-input-container>
<input mdInput placeholder="Sectors" [mdAutocomplete]="auto" [formControl]="sectorsCtrl">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let value of filteredSectors | async" [value]="value" >
{{ value.label }}
</md-option>
</md-autocomplete>
How can I adapt the code in order to use a remote API?
回答1:
You will have to get the remote data via service
and assign the data to a variable, in your example it will be assigned to allSectors
. Then it's usual business, running the filter on allSectors
, if allSectors
is an array of objects, than you have to specify on which property you want to run the filter. In my demo, I am doing it for sector.name
.
You can use displayWith
to control what value to show in input field.
HTML:
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let sector of filteredSectors | async" [value]="sector">
{{ sector.name }}
</md-option>
</md-autocomplete>
TS:
export class AutocompleteOverviewExample implements OnInit{
stateCtrl: FormControl;
filteredSectors: any;
allSectors;
constructor(private dataService: DataService) {
this.stateCtrl = new FormControl();
}
ngOnInit(){
this.dataService.fetchData()
.subscribe(
(data) => {
this.allSectors = data.customers;
this.filteredSectors = this.stateCtrl.valueChanges
.startWith(null)
.map(val => val ? this.filter(val) : this.allSectors.slice());
}
);
}
filter(name) {
return this.allSectors.filter(sector => new RegExp(`^${name}`, 'gi').test(sector.name));
}
displayFn(sector) {
return sector ? sector.name : sector;
}
}
Here's the Plunker.
来源:https://stackoverflow.com/questions/44308283/angular-2-materials-autocomplete-with-remote-data