Angular 2材质,自动完成远程数据

时间:2017-06-01 13:01:53

标签: api angular autocomplete angular-material2

我使用Angular 4和Materials 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 个答案:

答案 0 :(得分:0)

您必须通过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