Angular 2材质,可自动完成并带有远程数据 [英] Angular 2 materials, autocomplete with remote data

查看:68
本文介绍了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;
   }

}

这是柱塞.

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

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