2017-04-19 77 views
0

我有這樣的輸入域:角不更新數據列表的DOM元素

<input type="text" list="myList"> 
<datalist id="myList"> 
    <option *ngFor="let loc of locationList">{{ loc.description }}</option> 
</datalist> 

這是一個非常簡單的事情。 datalist提供了自動完成選項,它由一個數組填充。該數組由服務更新。

問題來了。無論服務是否升級陣列 - 都可以在控制檯上進行檢查,實際上它正在更新 - datalist的內容在另一次按鍵之前不會改變。

在Chrome中我發現ChangeDetectorRef.detectChanges()可以消除這個問題。但在Firefox下它仍然存在。當用戶按下Backspace時,Firefox只會更新datalist。如果他只是繼續打字,那不會。

有沒有辦法告訴Angular刷新綁定到這個數組的所有綁定?

回答

0

這裏使用的是HTML 5,沒有棱角。你依賴於瀏覽器的實現。 我建議你用舊的方式方法:

<div class="container" > 
    <div class="input-field col s12"> 
     <input type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter()> 
    </div> 
    <div class="suggestions" *ngIf="locationList.length > 0"> 
     <ul *ngFor="let loc of locationList" > 
      <li > 
       <a (click)="select(loc)">{{loc.description}}</a> 
      </li> 
     </ul> 
    </div> 
</div> 

更新您的組件使用此方法:

query: string; 
locationList: []; 

filter() { 
    if (this.query !== ""){ 
     this.locationList = this.service.getLocations().filter(function(el){ 
      return el.toLowerCase().indexOf(this.query.toLowerCase()) > -1; 
     }.bind(this)); 
    }else{ 
     this.locationList = []; 
    } 
} 

select(item){ 
    this.query = item; 
    this.locationList = []; 
} 

這裏更詳細的工作例如:http://4dev.tech/2016/03/tutorial-creating-an-angular2-autocomplete/

0

如果你調用一個Javascript外的Angular,你必須使用NgZone(基於ZoneJS框架)來更新你的Angular模型。

例如:

import {Component, NgZone} from '@angular/core'; 

@Component({ 
    ... 
}) 
export class YourComponent { { 

    locationList: any[]; 
    constructor(private ngZone: NgZone) {} 

    updateDataList() { 
    googleMapsToPromise().then(locations => { 
     this.locationList = location; 
     this.ngZone.run(() => { 
      console.log('model updated') 
     }); 
     } 
    } 
    } 

} 

文檔瀏覽:https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html

這裏googleMapsToPromise實現的例子:https://jamesbedont.com/2016/03/23/GoogleMapsApiIntroduction.html#geocode

+0

它仍然不起作用。當輸入字段中的文本被改變並且按下退格鍵時,Firefox只更新數據列表。沒有其他的鑰匙能做任何事 –

0

所有權利。這裏沒有任何修補區域的幫助。我花了將近兩天的時間試圖讓它工作,然後我扔了它,並在十分鐘內用這個替換了datalist

<input type="text" class="form-control" formControlName="location" [(ngModel)]="currentLocation"> 

<div class="panel panel-default panel-body datalist" *ngIf="locationList.length > 0 && !(locationList.length == 1 && locationList[0].description == currentLocation)"> 
    <ul> 
     <li *ngFor="let loc of locationList"><a (click)="changeLocation(loc.description)">{{ loc.description }}</a></li> 
    </ul> 
</div> 

這是一個Bootstrap面板,每當有東西可供選擇時都會出現。它適用於每個瀏覽器,並且沒有更新問題。另外我可以檢測用戶是否從列表中選擇了一個選項,因此我得到了有效的響應。添加一個裝載器微調器也是很容易的(我真的這樣做了,但我保持這個片段簡單)。

今日吸取教訓:不要嘗試在Angular中使用datalist。不要。