angularangular-reactive-forms

Angular Reactive forms - Default value for controls not working


I want to have a preselected option on my dropdown list. i set to preSelectedLegalType the value on ngOnInit but i can't display it.How can i display this value?

My ts file

export class BusinessDetailsComponent implements OnInit {
  legalTypes: any = ["Α.A.", "B.B.", "C.C.", "D.D.", "Ε.Ε."];
  preSelectedLegalType: string = this.stateService.legalEntity.LegalType;
   
  constructor(private stateService: StateService) {
    this.businessDetailsForm = this.createForm();
  }
 
  ngOnInit() {
    this.businessDetailsForm.controls['legalType'].setValue(
      this.preSelectedLegalType, {onlySelf: true}
    );
  }
 
  createForm() {
    return this.fb.group({
      legalType: [this.preSelectedLegalType, [Validators.required]],
      businessName: ['', {validators: [Validators.required]}]
    });
  }
}

html

<select class="form-control custom-select-text" id="legalType" formControlName="legalType" required>
  <option *ngFor="let legalType of legalTypes" [ngValue]="legalType" class="testhover" >{{legalType}}</option>
</select>

Solution

  • Use FormBuilder control() method to create controls in the Form as shown below.

    createForm() {
      return this.fb.group({
        legalType: this.fb.control(this.preSelectedLegalType, [Validators.required]),
        businessName: this.fb.control('', [Validators.required])
      });
    }
    

    The first argument of control() method takes the initial value, followed by the array of Validators.

    More about the control() of FormBuilder can be found here. You can find the complete example here in Stackblitz.