Setting value of [(ngModel)] upon first page load in Angular 2
So you want alertType
should be set to the selected value, whether it could be from your provided options
or from your defaultValue
(first option).
this could be done by using AfterViewInit
hook,
the modified code will be..
@Component({ selector: 'my-app', directives:[ SelectComponent ], template : `<select ui-select [options]="options" [(ngModel)]="alertType" [defaultValue]="'Select an alert Type'" #mySelect></select>{{alertType}}`})export class App implements AfterViewInit{ @ViewChild('mySelect', {read: ViewContainerRef}) mySelect;options = [ {id: 1, value: "item-1", selected: false}, {id: 2, value: "item-2", selected: true},//if all options will be false then defaultValue will be selected {id: 3, value: "item-3", selected: false}];alertType: any; ngAfterViewInit() { this.alertType = this.mySelect.element.nativeElement.value; }}
I have created a plunker, check this!!
You could try it like so:
options = [ {id:1, value:"item-1"}, {id:2, value:"item-2"}, {id:3, value:"item-3"}];alertType: any = options[0].id;
For your new question, you could leverage the selected
attribute in your ui-select component:
<option *ngIf="defaultValue" selected="true" value="-1">{{defaultValue}}</option>