Navigate to URLs Based on Angular Dropdown Selection
In this article, we’ll explore how to navigate to a URL based on the selection from an Angular Dropdown List component. This is particularly useful for creating dynamic navigation options in Angular applications.
Setup the HTML Template
First, we need to define the Dropdown List in HTML template. The Dropdown List component is configured with the dataSource, fields, and placeholder properties. The change event is bound to the onChange method, which is used to get the selected data along with the URL string.
<!-- app.component.html -->
<ejs-dropdownlist
id="ej2_demo"
[dataSource]="navigate_URL_Data"
(change)="onChange($event)"
[fields]="fields"
[placeholder]="waterMark"
></ejs-dropdownlist>
Define the Component Class
Next, we’ll define the component class in app.component.ts. This class will include the data source for the Dropdown List, the fields mapping, and the onChange method to handle the selection change event.
// app.component.ts
import { Component } from '@angular/core';
import { DropDownListModule } from '@syncfusion/ej2-angular-dropdowns';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
standalone: true,
imports: [DropDownListModule],
})
export class AppComponent {
public waterMark: string = 'EJ2 Dropdown List Demo';
public navigate_URL_Data = [
{
Title: 'Default Functionalities',
URL: 'https://ej2.syncfusion.com/angular/demos/#/fluent2/drop-down-list/default',
},
{
Title: 'Grouping and Icons',
URL: 'https://ej2.syncfusion.com/angular/demos/#/fluent2/drop-down-list/grouping-icon',
},
{
Title: 'Data Binding',
URL: 'https://ej2.syncfusion.com/angular/demos/#/fluent2/drop-down-list/data-binding',
},
{
Title: 'Object Value Binding',
URL: 'https://ej2.syncfusion.com/angular/demos/#/fluent2/drop-down-list/object-value-binding',
},
];
public fields: Object = { text: 'Title', value: 'URL' };
public onChange(args: any): void {
window.open(args.value, '_blank');
}
}
The navigate_URL_Data array contains the data for the dropdown list, with each item having a Title and a URL. The fields object maps the text and value properties to the corresponding fields in the data source. The onChange method uses window.open to navigate to the selected URL in a new browser tab.
By following these steps, you can easily create a Dropdown List in Angular that navigates to different URLs based on the user’s selection. You can find a sample implementation here.