'Angular 4 - Select default value in dropdown [Reactive Forms]

In Angular 4, I have the following configuration defined in a json config file.

 countries: ['USA', 'UK', 'Canada'];
 default: 'UK'

I need to display these in a dropdown using Reactive module.

Here is the code to do this (ts)

countries: string[] = [];
default: string;
...
this.countries = config.countries;
this.default = config.default;

html

<select id="country" formControlName="country"  >
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 

This does the job and displays the countries in a drop down. However, I also need to select a country by default and the default country comes from the 'default' key defined in json.

So, I tried doing something like this

{{ c }}

However, this does not work. By default an empty value if selected.

How can I make sure that a predefined value is selected by default?



Solution 1:[1]

Try like this :

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component {

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {
        this.countryForm = new FormGroup({
            country: new FormControl(null);
        });
        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

Solution 2:[2]

In Reactive forms. Binding can be done in the component file and usage of ngValue. For more details please go through the following link

https://angular.io/api/forms/SelectControlValueAccessor

import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form [formGroup]="form">
      <select formControlName="state">
        <option *ngFor="let state of states" [ngValue]="state">
          {{ state.abbrev }}
        </option>
      </select>
    </form>

       <p>Form value: {{ form.value | json }}</p> 
       <!-- {state: {name: 'New York', abbrev: 'NY'} } -->
    `,
})
export class ReactiveSelectComp {
  states = [
    {name: 'Arizona', abbrev: 'AZ'},
    {name: 'California', abbrev: 'CA'},
    {name: 'Colorado', abbrev: 'CO'},
    {name: 'New York', abbrev: 'NY'},
    {name: 'Pennsylvania', abbrev: 'PA'},
  ];

  form = new FormGroup({
    state: new FormControl(this.states[3]),
  });
}

Solution 3:[3]

In your component -

Make sure to initialize the formControl name country with a value.

For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,

....
this.myForm = this._fb.group({
  country:[this.default]
})

and also try replacing [value] with [ngValue].

EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this.

this.myForm.controls.country.controls.setValue(this.country) 

Solution 4:[4]

I was struggling and Found this Easy and Effective way from IntelliJ IDEA suggestion

<select id="country" formControlName="country"  >
  <option [defaultSelected]=true [value]="default" >{{default}}</option>
  <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 

And On your ts file assign the values

 countries = ['USA', 'UK', 'Canada'];
 default = 'UK'

Just make sure your formControlName accepts string, because you already assigned it as a string.

Solution 5:[5]

You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)] and further in component file assign default value to it.

In your_component_file.ts

this.selectedCountry = default;

In your_component_template.html

<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 

Plunker link

Solution 6:[6]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

In Chrome and Firefox works fine.

Solution 7:[7]

You can use the patch function for setting defaults with some of the values in your form group.

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component implements OnInit{

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {

        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

ngOnInit() {
    this.countryForm = new FormGroup({
      'country': new FormControl(null)
    }); 

    this.countryForm.patchValue({
      'country': default
    });

  }

Solution 8:[8]

<option [defaultSelected]="condition"> Default option here value</option>

condition must be true to select the input by default

To select for eg UK by default, we need to name the option et make the condition like this

<option [defaultSelected]="inputName.value==='UK' " #inputName> Default value </option>

to select UK by default and you must add the value attribute or use

<option [defaultSelected]="inputName.text==='UK' " #inputName> Default value </option>

Solution 9:[9]

Component: Default: string = '-1'; If dynamic then call this in your method or if static then call this inside constructor this.XYZFormGroup.controls['ABCList'].setValue(this.Default, {onlySelf: true}); HTML: <option value="-1">--Select a member--</option>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bellash
Solution 2 Victor
Solution 3
Solution 4 abrsh
Solution 5
Solution 6
Solution 7 Idris.AH
Solution 8
Solution 9 Shakti Srivastav