Home:ALL Converter>Angular - Reactive Form - Default selected value in dropdown

Angular - Reactive Form - Default selected value in dropdown

Ask Time:2018-01-11T19:29:08         Author:Rishi Vedpathak

Json Formatter

I am using angular's reactive form in which I have a dropdown. Refer plunk here

See below code.

<select class="form-control" id="contry" formControlName="country">
    <option *ngFor="let contry of countries" [value]="contry.id">{{contry.name}}</option>
</select>

Here I am not able to display default selected value. It always shows me a blank default value in dropdown. It is working fine in Template driven forms. And I also know it can be possible in reactive form by using

form.setValue or form.patchValue

Is there any better way that I can achieve this without setting any form value in my controller?

Author:Rishi Vedpathak,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48206012/angular-reactive-form-default-selected-value-in-dropdown
Ashraful Islam :

Try This \n\nthis.myForm = this._fb.group({\n country:this.countries[0]\n});\n\n\nand in template \n\n<option *ngFor=\"let contry of countries\" [value]=\"contry\">{{contry.name}}</option>\n\n\n\n set default value for the formcontrol and in template, bind value property with the whole contry object as you are pointing the full object in the .ts file \n",
2018-01-11T11:41:44
Gianluca Paris :

In your form initialization just add the default value to the form control\n\nthis.myForm = this._fb.group({\n country: this._fb.control(1)\n});\n\n\nYou can obviously change 1 with the id of your default value",
2018-01-11T11:38:37
yy