2017-06-01 78 views
1

我正在使用角4与材料2.角2材料,自动完成与远程数据

我已经成功地创建了一些使用数组数组的自动完成字段。在这里我的控制器:

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; 
} 

而且我的模板:

<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> 

我怎么能适应的代码,以便使用远程API?

回答

1

您将不得不通过service获取远程数据并将数据分配给一个变量,在您的示例中它将被分配到allSectors。然后,这是平常的业务,如果allSectors是一个对象数组,那么在allSectors上运行过滤器,而不是必须指定要在哪个属性上运行过滤器。在我的演示中,我正在为它做sector.name

您可以使用displayWith来控制在输入栏中显示的值。

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; 
    } 

} 

这里的Plunker

+3

我认为(我自己也遇到了同样的问题)@Bagbyte希望使用远程API来执行过滤。所以数据应该在'valueChanges'上获取 – GregoryHouseMD