3

I am using Angular 2 to build my application. This is my code so far:

Template

<select class="form-control input-xs" [(ngModel)]="filter.coordinatorId" name="coordinatorId" (ngModelChange)="onCoordinatorChange($event)">                                                              
    <option *ngFor="let coordinator of coordinators; let i = index" [value]="coordinator.id" [selected]="i==0">{{coordinator.name}}</option>                                    
</select>

Component

onCoordinatorChange(coordinatorId: number){
        alert(coordinatorId);
        //business logic
    }

As you can see, I set [value]="coordinator.id" in option so I am getting coordinator.id value in alert, and if I change it to coordinator.name then I will get that value. But here I want to get multiple values like coordinator.id,coordinator.name,coordinator.department etc. So one solution could be using comma separated but that will be ugly and hard to maintain if other parameters come. Do I have any other option to write my function something like:

onCoordinatorChange(coordinatorId: number, name: string, department: string){
            alert(coordinatorId);
            //business logic
}

2 Answers 2

2

Use [ngValue] instead of [value] and just set whole object as a value, that way you will pass entire object and you will have access to all its attributes:

<select class="form-control input-xs" [(ngModel)]="filter.coordinator" name="coordinatorId" (ngModelChange)="onCoordinatorChange($event)">                                                              
    <option *ngFor="let coordinator of coordinators; let i = index" [ngValue]="coordinator" [selected]="i==0">{{coordinator.name}}</option>                                    
</select>
Sign up to request clarification or add additional context in comments.

1 Comment

Both awesome answers came in almost no time, +1. Confused what to accept ;)
2

You can use [ngValue] instead of [value] and pass the coordinator instead of coordinator.id

[ngValue]="coordinator"

This would need to be changed to though

[(ngModel)]="filter.coordinator"

5 Comments

Both awesome answers came in almost no time, +1. Confused what to accept ;)
Accept Stefans. . . . . .
Really funny situation, haha! Write post on stackoverflow meta and ask for option to accept two answers. ;-)
Way to much hassle. I'm not suffering from lack of reps, so no worries ;-)
@GünterZöchbauer haha.. yeah you should start answering bounty questions only :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.