[英]how to load a new component by replacing an existing component in angular router
I have customerList component in which i am getting data from a service and rendering the data. 我有customerList组件,在其中我要从服务获取数据并呈现数据。 In each row if i am clicking on any name, i am trying to render to a new CustomerDetail component with different header and content.
在每一行中,如果我单击任何名称,则尝试呈现为具有不同标题和内容的新CustomerDetail组件。 I am able to load CustomerDetail component but its coming below customerList component.
我能够加载CustomerDetail组件,但是它位于customerList组件之下。
i tried to solve by routing, its not happening 我试图通过路由解决,它没有发生
app.component.html 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 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 customerList.component.ts
onSelect(customer){
console.log('onSelect method calls');
console.log(customer);
this.router.navigate(['/customer',customer.customerName]);
}
app-routing.module.ts 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 { }
You have to remove the <customer-list>
from you app.component.html 您必须从app.component.html中删除
<customer-list>
Add a catch-all route: 添加一个包罗万象的路线:
const routes: Routes = [
{ path: 'home', component: CustomerListComponent },
{ path:'customer/:customerName', component : CustomerDetailComponent},
// Add this route
{ path: '**', redirectTo: 'home' }
];
Furthermore change the link to: 此外,将链接更改为:
<a [routerLink]="['/customer', customer.customerName]">{{customer.customerName}}</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.