Skip to content

Instantly share code, notes, and snippets.

@klinki
Created September 29, 2016 14:05
Show Gist options
  • Save klinki/7c85c4d1aec4cfb06623bd5b510e412d to your computer and use it in GitHub Desktop.
Save klinki/7c85c4d1aec4cfb06623bd5b510e412d to your computer and use it in GitHub Desktop.
Angular 2 select
<h2>One way binding</h2>
<select [ngModel]="selectedItems" (ngModelChange)="onChange($event)" multiple>
<option [ngValue]="i" *ngFor="let i of collection">{{i.name}}</option>
</select>
<h2>Two way binding</h2>
<button>Select all</button><button>Clear selection</button>
<select [(ngModel)]="selectedItems" (ngModelChange)="onChange($event)" multiple>
<option [ngValue]="i" *ngFor="let i of collection">{{i.name}}</option>
</select>
<h2>Selected items</h2>
<p *ngFor="let selected of selectedItems">
{{selected.name}}
</p>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-select',
templateUrl: './select.component.html'
})
export class SelectComponent implements OnInit {
private collection = [
{name: "test"},
{name: "Test 2"},
{name: "test 3"}
];
selectedItems = [];
constructor() { }
ngOnInit() {
}
onChange(selection) {
this.selectedItems = selection;
}
clearSelection() {
this.selectedItems = [];
}
selectAll() {
this.selectedItems = this.collection.slice();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment