繁体   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