Wednesday, 7 December 2016

Sign up How to pass argument upstairs in Angular2

I have to pass an argument to a function.
<select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)">
   <option *ngFor="let item of _items">{{ item.name }}</option>
</select>
It's really important for me, because I have to pass that item.name argument to a http request. But unfortunately angular doesn't see that variable, because it's kinda downstairs... The function has to take item.name of actual chosen option in the select box. The function will be executed with every value change in that box.
Is there any solution to fix it? Or maybe there is another way to solve it?
Finally, the http request:
private updateWatchlistTable(name) {
  this.http.get('http://localhost:8080/api/points/getValue/' + name)
   .subscribe(res => this._watchlistElements = res.json());
  console.log(name);
}
console.log(name) returns undefined.
As you can see I need that argument item.name to make this http request work. Any help appreciated. :)
--------------------------------------------------------------------------------------------------------------------------

Best Answer;




With ngValue you can bind a value and
with (ngModelChange)="$event.name" you have access to the name.
With [(ngModel)]="selectedItem" you can get and set which item is selected.
<select class="chooseWatchlist" [(ngModel)]="selectedItem" (ngModelChange)="updateWatchlistTable($event.name)">
   <option *ngFor="let item of _items" [ngValue]="item">{{ item.name }}</option>
</select>

No comments:

Post a Comment