2017-06-01 82 views
1

我正在使用角4與材料2.角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

您將不得不通過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

+3

我認爲(我自己也遇到了同樣的問題)@Bagbyte希望使用遠程API來執行過濾。所以數據應該在'valueChanges'上獲取 – GregoryHouseMD