Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set default value in select-options using Angular 17

I may get downvoted to eternity but this is bugging me for a few hours now and unable to get it going!

I want to set Male as the default value.

Here’s the Angular HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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! Please help.

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading