Narendra CM Narendra CM - 10 months ago 91
Javascript Question

Angular2 Reactive forms - Set default value for form fields with dropdown

How can I set the default value for all forms fields in angular 2 reactive forms.

Here is the plnkr to reproduce the issue

Below code doesnot update dropdown values as it has object associated with it.

Note: Here I need to set default value for all form fields with response received from Backend API.


<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
<div class="form-group">
<select formControlName="country">
<option *ngFor="let country of masterCountries" [ngValue]="country">{{country.countryName}}</option>

<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" formControlName="name">
<small [hidden]=" || ( && !submitted)" class="text-danger">
Name is required (minimum 5 characters).
<!--<pre class="margin-20">{{ | json }}</pre>-->
<button type="submit" class="btn btn-default">Submit</button>
<div class="margin-20">
<div>myForm details:-</div>
<pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
<pre>Is myForm submitted?: <br>{{submitted | json}}</pre>
<pre>myForm value: <br>{{myForm.value | json}}</pre>


export class AppComponent implements OnInit {
public myForm: FormGroup;
public masterCountries: any[] = [{"countryCode":"AF","countryName":"Afghanistan"},{"countryCode":"AL","countryName":"Albania"},{"countryCode":"DZ","countryName":"Algeria"},{"countryCode":"AS","countryName":"American Samoa"},{"countryCode":"AD","countryName":"Andorra"}];

// Sample response received from backend api
public CountryResponse = {country: {"countryCode":"AF","countryName":"Afghanistan"}, name: 'test123'};
constructor(private _fb: FormBuilder) { }

ngOnInit() {

// the short way
this.myForm ={
country: [''],
name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],

.setValue(this.CountryResponse, {onlySelf: true});


save(model: User, isValid: boolean) {
this.submitted = true;
console.log(model, isValid);

Let me know if there is any other way to set the whole form.

Answer Source

Just change this:

            .setValue(this.CountryResponse, {onlySelf: true});

Into this:

const selectedCountry = this.masterCountries.find(country => country.countryCode === = selectedCountry;
            .setValue(this.CountryResponse, {onlySelf: true});

As said before you need to pass the exact same reference of the object

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download