0

I have couple of values coming from DB, and I want to set one of the value as default value for the drop-down form element, tried many way but couldn't fix the issue

my.ts:

phoneTypes;

defaultValue;

ngOnInit() {
  this.getPhoneTypes();
}

getPhoneTypes() {
  this.myService.getPhoneTypes().subscribe(data=>{
    this.phoneTypes= data;
  });
}

defaultValue = this.phoneTypes.name;

initForm() {
  phoneType : new FormControl()
}

my.html

<div id = "someId">
 <select formControlName="phoneType" [(ngModel)]="defaultValue">
   <option *ngFor="let phoneType of phoneTypes" [value]="phoneType.code" >{{phoneType.name}}</option>
 </select> 
</div>

but I see value is binding by default, I don't see the default value is coming.

AT82
  • 71,416
  • 24
  • 140
  • 167
user2108383
  • 239
  • 1
  • 9
  • 22
  • 3
    You are using formcontrol and ngModel. First choose either, template driven (or just ngModel) or reactive forms. Also I would expect you would get an error with using `formControlName` without a formgroup?? Anyway, read the docs: https://angular.io/guide/forms-overview – AT82 Jul 26 '19 at 16:49
  • I took ngModel from one of the example.. what is the other option that I can use to set the value. – user2108383 Jul 26 '19 at 17:37
  • did you read the documentation? There is a few issues in your code. First you need to read this: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular then if you choose to go with formcontrol, then there is `setValue` for setting the value at a later state: https://angular.io/api/forms/FormControl#setvalue – AT82 Jul 26 '19 at 17:41
  • 1
    yup I had gone through that and understood we shouldn't use ngModel for reactive forms.. – user2108383 Jul 26 '19 at 17:43
  • 1
    Thanks I'm able to populate the value with set value. – user2108383 Jul 26 '19 at 18:06

3 Answers3

1

Great answer already posted. Here I am posting a generalized solution to select default value in a select (dropdown) in a reactive forms scenario.

Suppose you've a model class Fruit and array of this class is returned through a server. To mock this situation I've created an observable using the 'of' rxjs operator.

import {from, of} from 'rxjs';
export class Fruit{
  public Id : number;
  public title : string;
}

  export const fruits=of([
    {Id:1, title:'Apple'},
    {Id:2, title:'Banana'},
    {Id:3, title:'Orange'},
    {Id:4, title:'Pineapple'},
    {Id:5, title:'Strawberry'}
  ]);

Now in the onInit lifecycle event of component where the fruits array observable is subscribed, I use the 'setValue' method of formControl to set the default value.

  ngOnInit(){
    this.formGroup=new FormGroup({
      fruit:new FormControl(null)
    });

    fruits.subscribe(response=>{
      this.fruitsArr = response;

      this.formGroup.controls['fruit'].setValue(this.fruitsArr[2]);
    });
  }

Please note that I'm selecting the 3rd element of fruitsArr as the default selected item of the select (dropdown) by writing below line..

this.formGroup.controls['fruit'].setValue(this.fruitsArr[2]);

Here is the html

<form [formGroup]="formGroup">
<select id="fruit" formControlName="fruit">
  <option *ngFor="let item of fruitsArr" [ngValue]="item">{{item.title}}</option>
</select>
</form>

Here is the working stackblitz.

Obaid
  • 2,563
  • 17
  • 15
1

To set the default value dynamically, i have used FormBuilderConfiguration of @rxweb/reactive-form-validators from where i can set the defaultValue of the formControl dynamically

You need to import ReactiveFormsModule in app module

Here is the complete component code:

import { Component, OnInit } from '@angular/core';
import { FormGroup } from "@angular/forms"
import { RxFormBuilder,FormBuilderConfiguration } from '@rxweb/reactive-form-validators';

import { User } from './user.model';

@Component({
    selector: 'app-phone-add',
    templateUrl: './phone.component.html'
})
export class phoneComponent implements OnInit {
    userFormGroup: FormGroup
      phoneTypes = [ "Type1","Type2"];

    constructor(
        private formBuilder: RxFormBuilder    ) { }

    ngOnInit() {
        let user = new User();
      var formBuilderConfig = new FormBuilderConfiguration();
        formBuilderConfig.propsConfig = {'phoneType': 
          {defaultValue:this.phoneTypes[0]}}
         this.userFormGroup = this.formBuilder.formGroup(user,formBuilderConfig);
    }
}
<div>
  <form  [formGroup]="userFormGroup">
    <div class="form-group">
      <label>Card Type</label>
      <select formControlName="phoneType" class="form-control">
  <option [value]="item" *ngFor="let item of phoneTypes">{{item}}</option>
      </select>
    </div>
    <button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
  </form>
</div>

Here is the working example

Ushmi Dave
  • 276
  • 1
  • 7
0

As suggested by @AJT_82 in the above comments, I removed [(ngModel)] attribute and used setVale to populate:

<div id = "someId">
 <select formControlName="phoneType">
   <option *ngFor="let phoneType of phoneTypes" [value]="phoneType.code" >{{phoneType.name}}</option>
 </select> 
</div>

In my.ts file

Here Phones is a formGroup

const phones = this.myForm.get('phones') as FormArray;
        phones.at(0).get('phoneType').setValue('Apple');
user2108383
  • 239
  • 1
  • 9
  • 22