【问题标题】:Angular 2 materials, autocomplete with remote dataAngular 2 材料,使用远程数据自动完成
【发布时间】:2017-06-02 03:03:50
【问题描述】:

我正在使用 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?

【问题讨论】:

    标签: api angular autocomplete angular-material2


    【解决方案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

    【讨论】:

    • 我认为(我自己也遇到了同样的问题)@Bagbyte 想要使用远程 API 来进行过滤。所以应该在valueChanges 上获取数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2017-10-21
    • 2017-12-29
    相关资源
    最近更新 更多