Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 select default first option

Tags:

angular

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>
like image 692
lars1595 Avatar asked Dec 13 '16 09:12

lars1595


4 Answers

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>
like image 73
Amruth Avatar answered Oct 17 '22 23:10

Amruth


This works for angular 4.1.3:

<option *ngFor="let t of sTypes; let i = index" [value]="t.value" [selected]="i==0">
like image 27
Adolfo Avatar answered Oct 17 '22 23:10

Adolfo


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>
like image 4
Alex Che Avatar answered Oct 17 '22 23:10

Alex Che


Or simply like this :)

<option *ngFor="let value of values; let i = index"
    [ngValue]="value" [attr.selected]="!i">
    {{item}}
</option>

Enjoy!

like image 4
Mikhaël Gerbet Avatar answered Oct 17 '22 23:10

Mikhaël Gerbet