Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 393
swati Avatar asked Oct 30 '17 09:10

swati


People also ask

How do I change the default value in a form group?

Set a default for a value list. In the Navigation Pane, right-click the form that you want to change, and then click Design View. Right-click the list box or text box control, and then click Properties or press F4.

How do I change value in reactive form?

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances. patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls.

How do you use Selectcontrolvalueaccessor?

How to use select controls with form directives. To use a select in a template-driven form, simply add an ngModel and a name attribute to the main <select> tag. In reactive forms, you'll also want to add your form directive ( formControlName or formControl ) on the main <select> tag.


1 Answers

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});     } } 
like image 129
Chandru Avatar answered Oct 13 '22 01:10

Chandru