如何通过替换 angular 路由器中的现有组件来加载新组件
how to load a new component by replacing an existing component in angular router
我有 customerList 组件,我在其中从服务获取数据并呈现数据。
在每一行中,如果我单击任何名称,我都会尝试呈现具有不同 header 和内容的新 CustomerDetail 组件。
我能够加载 CustomerDetail 组件,但它低于 customerList 组件。
我尝试通过路由解决,它没有发生
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<customer-list></customer-list>
<router-outlet></router-outlet>
customerList.component.html
<mat-cell *matCellDef="let customer">
<nav>
<a href routerLink="/customer" routerLinkActive="true" (click)="onSelect(customer)">{{customer.customerName}}</a>
</nav>
</mat-cell>
customerList.component.ts
onSelect(customer){
console.log('onSelect method calls');
console.log(customer);
this.router.navigate(['/customer',customer.customerName]);
}
app-routing.module.ts
const routes: Routes = [
{ path: 'home', component: CustomerListComponent },
{path:'customer/:customerName', component : CustomerDetailComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
您必须从 app.component.html
中删除 <customer-list>
添加 catch-all 路线:
const routes: Routes = [
{ path: 'home', component: CustomerListComponent },
{ path:'customer/:customerName', component : CustomerDetailComponent},
// Add this route
{ path: '**', redirectTo: 'home' }
];
进一步将 link 更改为:
<a [routerLink]="['/customer', customer.customerName]">{{customer.customerName}}</a>
我有 customerList 组件,我在其中从服务获取数据并呈现数据。 在每一行中,如果我单击任何名称,我都会尝试呈现具有不同 header 和内容的新 CustomerDetail 组件。 我能够加载 CustomerDetail 组件,但它低于 customerList 组件。
我尝试通过路由解决,它没有发生
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<customer-list></customer-list>
<router-outlet></router-outlet>
customerList.component.html
<mat-cell *matCellDef="let customer">
<nav>
<a href routerLink="/customer" routerLinkActive="true" (click)="onSelect(customer)">{{customer.customerName}}</a>
</nav>
</mat-cell>
customerList.component.ts
onSelect(customer){
console.log('onSelect method calls');
console.log(customer);
this.router.navigate(['/customer',customer.customerName]);
}
app-routing.module.ts
const routes: Routes = [
{ path: 'home', component: CustomerListComponent },
{path:'customer/:customerName', component : CustomerDetailComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
您必须从 app.component.html
中删除<customer-list>
添加 catch-all 路线:
const routes: Routes = [
{ path: 'home', component: CustomerListComponent },
{ path:'customer/:customerName', component : CustomerDetailComponent},
// Add this route
{ path: '**', redirectTo: 'home' }
];
进一步将 link 更改为:
<a [routerLink]="['/customer', customer.customerName]">{{customer.customerName}}</a>