如何通过替换角度路由器中的现有组件来加载新组件

时间:2019-06-10 10:05:10

标签: angular angular6 angular-routing angular-router

我有customerList组件,在其中我要从服务获取数据并呈现数据。 在每一行中,如果我单击任何名称,则尝试呈现为具有不同标题和内容的新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 { }

1 个答案:

答案 0 :(得分:1)

您必须从app.component.html中删除<customer-list>

添加一个包罗万象的路线:

const routes: Routes = [
  { path: 'home', component: CustomerListComponent },
  { path:'customer/:customerName', component : CustomerDetailComponent},
  // Add this route
  { path: '**', redirectTo: 'home' }
];    

进一步将链接更改为:

 <a [routerLink]="['/customer', customer.customerName]">{{customer.customerName}}</a>