Another solution is a custom directive that will listen for changes to the <option> list and select the first element if none are 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 the <select> element as follows:
<select ... mySelectFirstOption>
source share