📅  最后修改于: 2023-12-03 15:03:32.073000             🧑  作者: Mango
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.
To set up pathmatch in Angular, you need to follow these steps:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];
@NgModule({
imports: [
RouterModule.forRoot(routes),
],
exports: [
RouterModule,
],
})
<router-outlet></router-outlet>
Pathmatch can be of four types:
{ path: 'home', component: HomeComponent },
{ path: 'admin', loadChildren: './admin/admin.module#AdminModule' },
{ path: '**', component: NotFoundComponent }
{ path: 'book/:id(\\d+)', component: BookDetailComponent },
Pathmatch parameters can be used to pass data to a component or to extract data from a URL.
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
});
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
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.