How do i select the first option in a select by default in angular 2 the following code don't seems to work.
<select id="sType" class="form-control" [(ngModel)]="params.searchType">
<option *ngFor="let t of sTypes" [ngValue]="t.value" [attr.selected]="$index == 0 ? true : null">{{t.name}}</option>
</select>
You can select first option by default using index value.
<select id="sType" class="form-control" [(ngModel)]="params.searchType">
<option *ngFor="let t of sTypes; let i = index" [attr.value]="t.value" [attr.selected]="i == 0 ? true : null">{{t.name}}</option>
</select>
This works for angular 4.1.3:
<option *ngFor="let t of sTypes; let i = index" [value]="t.value" [selected]="i==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>
Or simply like this :)
<option *ngFor="let value of values; let i = index"
[ngValue]="value" [attr.selected]="!i">
{{item}}
</option>
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With