Jack_of_All_Trades
Jack_of_All_Trades

Reputation: 11468

passing variable from ngFor to the component's method

What I want to achieve:

Everytime the user selects some option on upper-select in the code below, I want to execute the component's method onSelectSampleType with the selected object as parameter which sets some public property of component to the passed parameter.

<select (change)="onSelectSampleType(SampleType)">
  <option  *ngFor="let SampleType of sampleTypeList">{{ SampleType }}</option>
</select>

<select *ngIf="selectedSample"">
  <option *ngFor ="let subType of selectedSampleType.subType">{{ subType }}</option>
</select>

Problem: the SampleType parameter in onSelectSampleType() method which is supposed to capture SampleType of ngFor directive is capturing nothing and passing undefined value. I think the scope of SampleType variable inside ngfor directive is just limited to tag.

Is there any way to accomplish what I want to achieve?

Upvotes: 2

Views: 6258

Answers (3)

Dimanoid
Dimanoid

Reputation: 7279

Try this

<select (change)="onSelectSampleType(sel.value)" #sel>
  <option *ngFor="let SampleType of sampleTypeList; let i = index" [value]="i">{{ SampleType }}</option>
</select>

you should get index of selected option i think

Upvotes: 3

RK_Aus
RK_Aus

Reputation: 946

You can pass the value as below:

<select (change)="onSelectSampleType(selectedItem.value)" #selectedItem>
    <option *ngFor="let SampleType of sampleTypeList;let i=SampleType" [value]="SampleType">{{ SampleType }}</option>
</select>

TypeScript:

public sampleTypeList = ["SampleType1", "SampleType2", "SampleType3"];

public onSelectSampleType(sampleType: string) {
    console.log(sampleType);
}

Upvotes: 0

cmrn
cmrn

Reputation: 1103

The problem with your code is that you're trying to access the SampleType variable outside of the scope of the ngFor directive. Since you're outside of the scope you can't access the variable, so your (change) callback doesn't receive the data you want.

If the only purpose of your callback is to set the selectedSampleType property on your component, you can just use ngModel to bind the control to selectSampleType directly:

<select [(ngModel)]="selectedSampleType">
  <option  *ngFor="let SampleType of sampleTypeList">{{ SampleType }}</option>
</select>

If you require a more complex callback, you can use $event.target.value to get the value of the option which triggered the (change) event:

<select (change)="onSelectSampleType($event.target.value)">
  <option  *ngFor="let SampleType of sampleTypeList">{{ SampleType }}</option>
</select>

You can find more information about Angular 2 event binding here: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#event-binding

Upvotes: 1

Related Questions