【问题标题】:Angular2 ngModel not updated after async callback异步回调后Angular2 ngModel未更新
【发布时间】:2017-03-14 11:04:03
【问题描述】:

为什么 angular2 双向数据绑定在这种情况下不起作用?

<span style="color:white">{{searchLocation}}</span>
<input  name="searchLocation" type="text" placeholder="Search" [(ngModel)]="searchLocation">
<button class="btn btn-outline-success" type="submit" (click)="search()">Search</button>

目标组件为HeaderComponent

export class HeaderComponent implements OnInit {

  searchLocation: string;
  @Output() locationFound: EventEmitter<Position> = new EventEmitter<Position>();

  constructor(private _locationService: LocationService) { }

  ngOnInit() {
     this.searchLocation ="";
  }

  search():void{

    this._locationService.geocodeAddress(this.searchLocation)
        .subscribe((position:Position)=>{
          this.searchLocation ="new value";
          this.locationFound.emit(position);
    });
  }
}

在订阅块之后,searchLocation 发生了变化,但视图没有更新。

希望有人能帮帮我

【问题讨论】:

  • 我不知何故错过了应该更新searchLocation 的部分。我只看到this.searchLocation =""; 两次,变化不大;-)。

标签: angular data-binding


【解决方案1】:
      this.searchLocation ="";

searchLocation 被赋值为 null。如果 null 存在,它将不会更新 DOM。尝试给出一些有效的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多