2017-04-19 74 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。不要。