Gulmuhammad Akbari
Gulmuhammad Akbari

Reputation: 2036

ng-select get value by id

I have two ng-select element as below:

<ng-select name="category_1" #category_1> ... </ng-select>

<ng-select name="category_2" #category_2 (change)='getBothValues(category_1.value,category_2.value)'> ... </ng-select>

As you see in second ng-select, I want to get selected value of the both select boxes in getBothValues() by id but it is not working.

Upvotes: 0

Views: 2490

Answers (1)

Benny Halperin
Benny Halperin

Reputation: 2332

The params you pass with (change) are not per their spec. What is passed is the selected option. I suggest you do the following to achieve the same (working demo here):

HTML

<p>
  List of Cars
</p>
<ng-select #category_1
  [items]="cars"
  bindLabel="name"
  placeholder="Select car"
  [(ngModel)]="selectedCar">
</ng-select>
<p>
  List of Colors
</p>
<ng-select #category_2
  [items]="colors"
  bindLabel="name"
  placeholder="Select color"
  [(ngModel)]="selectedColor"
  (change)="getBothValues($event)">

</ng-select>

TS

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  selectedCar: any;
  cars = [
        { id: 1, name: 'Volvo' },
        { id: 2, name: 'Saab' },
        { id: 3, name: 'Opel' },
        { id: 4, name: 'Audi' },
    ];
  selectedColor: any;
  colors = [
        { id: 1, name: 'Red' },
        { id: 2, name: 'Green' },
        { id: 3, name: 'Silver' }
    ];

  getBothValues(v1: any): void {
    console.log(this.selectedColor, this.selectedCar);
  }
}

Upvotes: 2

Related Questions