Angular 2 材料,使用远程数据自动完成 [英] Angular 2 materials, autocomplete with remote data

查看:24
本文介绍了Angular 2 材料,使用远程数据自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Angular 4 与材料 2 结合使用.

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

还有我的模板:

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

How can I adapt the code in order to use a remote API?

推荐答案

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

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.

您可以使用 displayWith 来控制要在输入字段中显示的值.

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

}

这是 Plunker.

这篇关于Angular 2 材料,使用远程数据自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆