簡體   English   中英

數據更新,angular2和打字稿后視圖中的值未更新

[英]value not updating in the view after data update , angular2 and typescript

這是我的ngOnInit函數

 instance.input = document.getElementById('google_places_ac');
        autocomplete = new google.maps.places.Autocomplete(instance.input, { types: ['(cities)']});
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            instance.setValue(place.address_components[3].long_name, place.address_components[2].long_name, place.address_components[1].long_name);

         });

這是我的setValue()函數

public setValue(a,b,c) {
    this.coutnry = a;
    this.state = b;
    this.city = c;
    this.sharedService.country = this.coutnry;
    this.sharedService.city = this.city;
    this.sharedService.state = this.state;
    console.log(a, b, c);
}

下面是我的html模板,用於顯示和獲取值

 <input id="google_places_ac" attr.state="{{state}}" attr.country="{{coutnry}}" name="google_places_ac" type="text" value="{{city}}" class="form-control" />

問題是一旦place_changed函數,我的html屬性就不會更新, place_changed有什么我需要做的事情來獲取視圖上的更新值嗎?

您可以查看此angular2官方文檔以設置屬性,

速查表-https: //angular.io/docs/ts/latest/cheatsheet.html

<input id="google_places_ac" [attr.state]="state" [attr.country]="coutnry"
name="google_places_ac" type="text" value="{{city}}" class="form-control" />

更新資料

import { Component, ChangeDetectorRef } from 'angular2/core';

constructor(private cdr:ChangeDetectorRef) {
}
public setValue(a,b,c) {
    this.coutnry = a;
    this.state = b;
    this.city = c;
    this.sharedService.country = this.coutnry;
    this.sharedService.city = this.city;
    this.sharedService.state = this.state;
    console.log(a, b, c);
    this.cdr.detectChanges();
}

您應該通過將屬性包裝在[]來使用屬性綁定

<input id="google_places_ac" [attr.state]="state" [attr.country]="coutnry" 
 name="google_places_ac" type="text" [value]="city" class="form-control" />

coutnry件事是,您在書寫country文字時coutnrycoutnry就像您在兩個地方寫coutnry一樣。

this.sharedService.country = this.coutnry; //in constructor

attr.country="{{coutnry}}" //second place

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM