hơn Một giải pháp là chỉ thị tùy chỉnh, mà sẽ nghe <option>
s thay đổi danh sách và chọn mục đầu tiên nếu không được chọn.
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'));
}
}
}
Và sau đó bạn có thể sử dụng nó với <select>
yếu tố như thế này:
<select ... mySelectFirstOption>
Nguồn
2017-10-06 07:43:08
Dường như không hoạt động với Angular 4.4.4 và dạng điều khiển mô hình. –