Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngModel not updated after async callback

Why angular2 two way data binding doesn' t work in this scenario ?

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

The target component is 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);
    });
  }
}

After the subscribe block the searchLocation change but the view is not updated.

I hope somebody can help me

like image 375
Gianpolo Avatar asked Dec 07 '25 16:12

Gianpolo


1 Answers

      this.searchLocation ="";

searchLocation is assigned to null. If null is present it won't update the DOM. Try giving some valid string.

like image 135
Aravind Avatar answered Dec 10 '25 12:12

Aravind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!