Reputation: 727
How to pass variable from template to typescript from *ngFor
.
I am using for loop as:
<select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple>
<option *ngFor="let region of all_regions" [value]="region.id">{{region.name}}</option>
</select>
Now I want to send countries for region selected to ts i.e. in region.countries in onregionchange()
How can I achieve this in angular2
Upvotes: 1
Views: 1428
Reputation: 3484
In your function onregionchange()
you need to pass all the options. Like change($event.target.options)
.
And in TS file you need to extract selected ones since you are getting all the variables in it. Something like :
onregionchange(countries) {
this.selectedregions = Array.apply(null,countries)
.filter(country => country.selected)
.map(country=> country.value)
}
Check this plunkr
Upvotes: 5
Reputation: 6233
Well, you got a onchange
handler on select
. So, you can use that,
<select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple>
<option *ngFor="let region of all_regions" [value]="region.id">{{region.name}}</option>
</select>
function onregionchange(e){
console.log(e.target.value)
}
As you have given region.id
as option
value, you will get region.id
of the selected option. I hope you can get region.country
from that.
Upvotes: 0