Skip to content

Instantly share code, notes, and snippets.

@Alger23
Last active October 7, 2017 06:31
Show Gist options
  • Select an option

  • Save Alger23/0ff02e964e025bece5024ac00e5d4cf6 to your computer and use it in GitHub Desktop.

Select an option

Save Alger23/0ff02e964e025bece5024ac00e5d4cf6 to your computer and use it in GitHub Desktop.
Get selection from "select" in angular 2
<select (click)="onChange($event)">
    <!-- WORKING -->
    <!-- <option *ngFor="let item of items" (click)="select(item.id)">{{item.text}}</option> -->

    <!-- NOT WORKING -->
    <ng-template ngFor let-item [ngForOf]="items">
        <optgroup *ngIf="item.children" label="{{item.text}}">
            <option *ngFor="let child of item.children" [value]="child.id">{{child.text}}</option>
        </optgroup>
        <option *ngIf="!item.children" [value]="item.id">{{item.text}}</option>
    </ng-template>
</select>
select($event) {
    this.selected = $event.target.selectedOptions[0].value;
}

stackoverflow

If you don't need two-way data-binding:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let i of devices">{{i}}</option>
</select>
onChange(deviceValue) {
    console.log(deviceValue);
}

For two-way data-binding, separate the event and property bindings:

<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">
    <option [value]="i" *ngFor="let i of devices">{{i}}</option>
</select>
export class AppComponent {
  devices = 'one two three'.split(' ');
  selectedDevice = 'two';
  onChange(newValue) {
    console.log(newValue);
    this.selectedDevice = newValue;
    // ... do other stuff here ...
}

If devices is array of objects, bind to ngValue instead of value:

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
  <option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
{{selectedDeviceObj | json}}
export class AppComponent {
  deviceObjects = [{name: 1}, {name: 2}, {name: 3}];
  selectedDeviceObj = this.deviceObjects[1];
  onChangeObj(newObj) {
    console.log(newObj);
    this.selectedDeviceObj = newObj;
    // ... do other stuff here ...
  }
}

Plunker - does not use

Plunker - uses and uses the new forms API

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment