In Angular, we can use the
Select elements controls and allow users to choose one or more options from a list of predefined values.
First, import FormsModule in your "app.module.ts" file if haven't imported it already. This is necessary for Angular's two-way data binding to work with forms.
import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
In your component's HTML file, use the
<h2>Select a City</h2> <select [(ngModel)]="selectedCity" (change)="onCityChange($event)"> <option *ngFor="let city of cities" [value]="city">{{ city }}</option> </select> <p>Display Selected City: {{ selectedCity }}</p>
we can use the "ngModel" directive to bind the selected value to a variable in your component.
Angular's [(ngModel)] directive is used for two-way data binding between the
Dynamic list rendering using Angular *ngFor: Angular's `*ngFor` directive is used to iterate over a collection of items and dynamically generate
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { selectedCity: string = 'red'; // Default selected city // Array of cities options cities: string[] = ['New York', 'Palo Alto', 'New Jersey', 'Miami']; // Event handler for change event onCityChange(event: Event): void { this.selectedCity = (event.target as HTMLSelectElement).value; } }
In your component's TypeScript file, define the "selectedCity" variable.
We have a
The
The (change) event is bound to the `onCityChange()` method to handle changes in the selected value.
When the user selects a different city, the `selectedCity` property is updated, and the corresponding message is displayed.
Now, the "selectedCity" variable in our component will always hold the value of the currently selected option in the dropdown menu.
We can use this variable to perform any necessary logic based on the user's selection.