📜  pathmatch angular - TypeScript (1)

📅  最后修改于: 2023-12-03 15:03:32.073000             🧑  作者: Mango

Pathmatch in Angular with TypeScript

In Angular, pathmatch is used to match the URL of a route with a specific component or view. It can be used to navigate to a particular page or load different components based on the URL.

Setting up Pathmatch in Angular

To set up pathmatch in Angular, you need to follow these steps:

  1. Import the required modules
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
  1. Define routes
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
];
  1. Add the RouterModule to your application
@NgModule({
  imports: [
    RouterModule.forRoot(routes),
  ],
  exports: [
    RouterModule,
  ],
})
  1. Add router outlet to your application
<router-outlet></router-outlet>
Pathmatch Types

Pathmatch can be of four types:

  1. Exact match - Matches the full URL path
{ path: 'home', component: HomeComponent },
  1. Prefix match - Matches if the URL begins with the given path
{ path: 'admin', loadChildren: './admin/admin.module#AdminModule' },
  1. Wildcard match - Matches any URL that doesn't match other routes
{ path: '**', component: NotFoundComponent }
  1. Regular Expression match - Matches a URL based on a regular expression
{ path: 'book/:id(\\d+)', component: BookDetailComponent },
Pathmatch Parameters

Pathmatch parameters can be used to pass data to a component or to extract data from a URL.

Passing Parameters

To pass parameters to a component, you can add a parameter to the path

{ path: 'product/:id', component: ProductComponent }

Then, you can pass the parameter in the URL like this:

http://localhost:4200/product/123

In the component, you can access the parameter like this:

this.route.params.subscribe(params => {
  console.log(params['id']); // Output: 123
});
Extracting Parameters

To extract parameters from a URL, you can add a parameter to the path with a regular expression

{ path: 'book/:id(\\d+)', component: BookDetailComponent }

Then, you can extract the parameter in the component like this:

let id = this.route.snapshot.paramMap.get('id'); // Output: 123
Conclusion

Pathmatch is an important part of Angular routing. It helps to match the URL with the appropriate component and also pass or extract data to and from the component. With these basic concepts, you can easily set up pathmatch in your Angular application.