In Angular 2 and later versions, you can use the built-in Router module to handle routing and create URLs for your application.
To define a route, you need to import the RouterModule and define an array of Routes. Each route object should have a path property, which specifies the URL path for the route, and a component property, which specifies the component to be displayed when the route is activated.
Here’s an example of how to define a route for a component:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MyComponent } from './my-component';
const routes: Routes = [
{ path: '', component: MyComponent },
{ path: 'other', component: OtherComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this example, the RouterModule.forRoot() method is used to configure the router with the routes defined in the routes array. The exports property of the NgModule decorator makes the RouterModule available for use in other modules.
To create a URL for a route, you can use the routerLink directive in your templates. For example:
<a routerLink="/">Home</a>
<a routerLink="/other">Other</a>
This will generate links to the / and /other paths, which will activate the MyComponent and OtherComponent components, respectively.
You can also use the Router service in your components to navigate programmatically, like this:
import { Router } from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: './my-component.html'
})
export class MyComponent {
constructor(private router: Router) {}
goToOther() {
this.router.navigate(['/other']);
}
}
This will navigate to the /other path when the goToOther() method is called.
