Search code examples
angularangular6angular-routingangular-router

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. 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. I am able to load CustomerDetail component but its coming below customerList component.

i tried to solve by routing, its not happening

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 { }

Solution

  • You have to remove the <customer-list> from you app.component.html

    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>