Angular 2 - How To Set Default Selected Option


Answer :

<select [(ngModel)]="defaultValue">   <option>AM</option>   <option>PM</option> </select> 
export class MyComponent {   defaultValue = 'PM'; } 

Usually it's done like

<select [(ngModel)]="defaultValue">   <option *ngFor="let value of values" [ngValue]="value">{{value}}</option> </select>  export class MyComponent {   values = ['AM', 'PM'];   defaultValue = this.values[1]; } 

Hint For non-string values use `[ngValue]="..."

<select [(ngModel)]="defaultValue">   <option [ngValue]="values[0]">AM</option>   <option [ngValue]="values[2]">PM</option> </select> 

For a template driven form, I did this and got default selection.

<select [(ngModel)]="defaultOption" name="identification">                 <option [value]=null>Select</option>                 <option *ngFor="let option of identification" [value]="option.id"> {{ option.name }} </option>               </select> 

and in the component.ts file,

   identification = [     { id: 1, name: 'Passport'},     { id: 2, name: 'Adhaar'},     { id: 3, name: 'Driver\'s license'},     ];     defaultOption = null; 

On load, we could get Select as default selected.


I don't know why so much long answers here.

Short Answer :

use [selected]="isSelected" in your option tag!

Solution :

<select>   <option [selected]="isSelected">AM</option>   <option>PM</option> </select> 

Source:

https://medium.com/@phismonster/set-default-value-for-select-in-angular-2-27f0da413935

Edit 1 : Example with array :

arr = [{str: 'A', isSelected: false}, {str: 'B', isSelected: true}, {str: 'C', isSelected: false}, {str: 'D', isSelected: false}, ];  <select>     <option *ngFor="let a of arr" value="a.str" [selected]="a.isSelected">{{a.str}}</option> </select> 

link with working example : https://stackblitz.com/edit/selected-test


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable