Home > front end >  how to set a default value in a ng-select inside a reactive form
how to set a default value in a ng-select inside a reactive form

Time:10-27

Hello I'm trying to use a ng-select inside my angular reactive Form, I have just done it works but I couldn't set a default value (sample Male) in the ng-select, how can I do this?

HTML

<form [formGroup]="demographyForm">
                
    <section >
        <h2 >{{ labels[0] }}</h2>
        <ng-select
            style="max-width: 130px;"
            formControlName="gender"
            [clearable]="false"
            [searchable]="false"
            [virtualScroll]="true">
          <ng-option [value]="">Gender</ng-option>
          <ng-option *ngFor="let gender of genders" [value]="gender">{{gender}}
          </ng-option>
        </ng-select>
   </section>
</form>

TS

genders: string[] = ['Male', 'Female'];
constructor(private fb: FormBuilder) {}

demographyForm = this.fb.group({
    gender: ['', [Validators.required]]})


get gender() {
    return this.demographyForm.get('gender');
}

CodePudding user response:

You can set the default value by setting it inside the fb.

import { Component, VERSION } from '@angular/core';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  constructor(private fb: FormBuilder) {}

  labels: string[] = ['Gender', 'Civil Status', 'Age Range'];
  genders: string[] = ['Male', 'Female'];

  demographyForm = this.fb.group({
    gender: ['Male'],
  });
}
  • Related