• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Angular 2 材料,使用远程数据自动完成

用户头像
it1352
帮助1

问题说明

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

正确答案

#1

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhefjhja
系列文章
更多 icon
同类精品
更多 icon
继续加载