How do i select the first option in a select by default in angular 2 the following code don\'t seems to work.
This works for angular 4.1.3:
<option *ngFor="let t of sTypes; let i = index" [value]="t.value" [selected]="i==0">
try using this
<select id="sType" class="form-control" [(ngModel)]="params.searchType" (ngModelChange)="onChange($event)">
<option *ngFor="let t of sTypes" [Value]="t.value">{{t.name}}</option>
</select>
in controller/component use-
this.params.searchType=sTypes[0]
onChange(updatedValue) {
this.params.searchType = updatedValue;
//other code
}
Reactive form controls
You can also set value in component using rform.controls
this.rForm.controls['id'].setValue(this.array[0].id);
You are mixing two things that cannot work together, as they conflict: ngModel and selected. If you bind with params.searchType you have to initialize params.searchType to the default value you want: this.params.searchType = sTypes[0];
One more solution is the custom directive, which will listen to <option>
s list changes and select the first item if none selected.
import { AfterViewInit, Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[mySelectFirstOption]'
})
export class SelectFirstOptionDirective implements AfterViewInit {
private observer: MutationObserver;
constructor(
private elementRef: ElementRef,
private renderer: Renderer2) {
if ((elementRef.nativeElement.tagName || '').toLowerCase() !== 'select') {
throw new Error('mySelectFirstOption directive can only be applied to <select> elements');
}
}
ngAfterViewInit() {
setTimeout(() => this.trySelectFirstOption(), 0);
this.observer = new MutationObserver(mutations => this.trySelectFirstOption());
const config: MutationObserverInit = { childList: true };
this.observer.observe(this.elementRef.nativeElement, config);
}
private trySelectFirstOption() {
const nativeElement = this.elementRef.nativeElement;
if (nativeElement.options.length > 0 && nativeElement.selectedIndex === -1) {
this.renderer.setProperty(nativeElement, 'value', nativeElement.options[0].value);
nativeElement.dispatchEvent(new Event('change'));
}
}
}
And then you can use it with <select>
element like this:
<select ... mySelectFirstOption>
<select class="form-control" [(ngModel)]="selectedCDM" >
<option *ngFor="let cdm of CDMs;let i = index" [ngValue]='cdm'>
{{cdm.Name}}
</option>
</select>
CDMs is an array of objects, where an object has Id and Name as attribute. And selectedCDM is set to first element of CDMs array