Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get custom html attribute values in angular2

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
}
like image 907
Imad Avatar asked Apr 15 '26 08:04

Imad


2 Answers

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>
like image 92
Stefan Svrkota Avatar answered Apr 17 '26 03:04

Stefan Svrkota


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"
like image 36
Günter Zöchbauer Avatar answered Apr 17 '26 04:04

Günter Zöchbauer