简体   繁体   English

如何在ngfor中将变量从模板传递到ts

[英]How to pass variable from template to ts in ngfor

How to pass variable from template to typescript from *ngFor . 如何从*ngFor将变量从模板传递到打字稿。

I am using for loop as: 我使用for循环为:

 <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 ie in region.countries in onregionchange() 现在,我想将所选区域的国家/地区发送到ts,即在region.countries中onregionchange()

How can I achieve this in angular2 我如何在angular2实现这一angular2

In your function onregionchange() you need to pass all the options. 在函数onregionchange()您需要传递所有选项。 Like change($event.target.options) . 就像change($event.target.options)

And in TS file you need to extract selected ones since you are getting all the variables in it. 在TS文件中,由于要获取其中的所有变量,因此需要提取选定的文件。 Something like : 就像是 :

onregionchange(countries) {
    this.selectedregions = Array.apply(null,countries)
      .filter(country => country.selected)
      .map(country=> country.value)
  }

Check this plunkr 检查这个笨蛋

Well, you got a onchange handler on select . 好吧,您在select上有一个onchange处理程序。 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. 给定region.id作为option值后,您将获得所选选项的region.id I hope you can get region.country from that. 希望您能从中获得region.country

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM