angularselectngmodel

Set default value in select-options using Angular 17


I want to set Male as the default value.

Here's the Angular HTML:

<select name="gender" id="gender" [(ngModel)]="registration.gender">
  <option value="male">Male</option>
  <option value="female">Female</option>
  <option value="others">Others</option>
</select>

My .TS file:

export class Registration implements OnInit {
  public patients = [] as Patient[];
  public patient = {} as Patient;
  public registration = {} as Registration;
  //registration.gender = 'male';
  gender = 'male';
}

I have tried several other methods but I'm unable to set male as the default selected value! What can I try next?


Solution

  • We can just initialize the value with the property gender as male.

    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [FormsModule],
      template: `
        <select name="gender" id="gender" [(ngModel)]="registration.gender">
          <option value="male">Male</option>
          <option value="female">Female</option>
          <option value="others">Others</option>
        </select>
      `,
    })
    export class App {
      public patients = [] as any[];
      public patient = {} as any;
      // this will also work, else go for ngOnInit!
      //public registration = { gender: 'male' } as any;
      public registration = {} as any;
      //registration.gender = 'male';
      gender = 'male';
    
      ngOnInit() {
        this.registration.gender = 'male';
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo