ADVERTISEMENTS

How can you initialize a select box on page load in angular

We can use the ngOnInit lifecycle hook to initialize the options for a select box when the component loads in Angular. It is a method that is automatically called by Angular after the component's constructor and the component's input properties have been set. In this method, we can set the options for the select box using the component's properties or by calling a service to retrieve the options.

The following example will explain about initialization of select box with options on page load in an Angular component :

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <select [(ngModel)]="selectedOption">
      <option *ngFor="let option of options" [value]="option.value">{{ option.label }}</option>
    </select>
  `,
})
export class ExampleComponent implements OnInit {
  options: any[] = [];
  selectedOption: any;

  ngOnInit() {
    this.options = [
      { value: 'option1', label: 'Option 1' },
      { value: 'option2', label: 'Option 2' },
      { value: 'option3', label: 'Option 3' },
    ];
  }
}

 

Above, we explained that the options array is defined in the component class and is set in the ngOnInit method. The *ngFor directive is used to loop through the options and create an option element for each one. The [(ngModel)] directive binds the selected option to the selectedOption property.

Angular is a javaScript framework for building single page web applications. You can learn angular from our Angular Tutorials and Angular Examples

ADVERTISEMENTS