Skip to content
Angular Essentials
GitHub

Sports route

Create sports component

ng g c forms/sports --skip-tests=true
@Component({
    selector: 'app-sports',
    standalone: true,
    templateUrl: './sports.component.html',
    styleUrls: ['./sports.component.scss'],
    imports: [CommonModule, CardComponent]
})
export class SportsComponent implements OnInit {

    sportCards: Card[] = [];

    ngOnInit(): void {
        this.sportCards = [
            {
                id: UUIDUtil.getUUIDAsString(),
                name: 'Football',
                price: 1500,
                imageUrl: 'https://upload.wikimedia.org/wikipedia/commons/1/1d/Football_Pallo_valmiina-cropped.jpg',
                description: 'Football description'
            },
            {
                id: UUIDUtil.getUUIDAsString(),
                name: 'Football Boot',
                price: 6000,
                imageUrl: 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/AdidasEtruscoBoot.jpg/230px-AdidasEtruscoBoot.jpg',
                description: 'Football description'
            }
        ];
    }
}
<app-card [cards]="sportCards"></app-card>

Registering sports as the route

Routes represents a route configuration for the Router service. An array of Route objects, used in Router.config and for nested route configurations in Route.children.

Route is a configuration object that defines a single route.

Define routes in Routes array. When an application starts, it navigates to the empty route by default. Here, we configured the router to redirect to a named route sports by default.

The pathMatch property, which is required for redirects, tells the router how it should match the URL provided in order to redirect to the specified route. Since pathMatch: full is provided, the router will redirect to sports if the entire URL matches the empty path (”).

// sports.routes.ts
export const routes: Routes = [
  { path: '', redirectTo: 'sports', pathMatch: 'full' },
  { path: 'sports', component: SportsComponent }
];

Add sports routes to header

  • Assign the anchor tag that you want to add the route to the routerLink attribute.
  • Set the value of the attribute to the component to show when a user clicks on each link.
  • Update your component template to include router-outlet element, an element that informs Angular to update the application view with the component for the selected route.
<!--header.component.html-->
<mat-toolbar color="primary">
    <span>Angular Basic</span>
    <button mat-button routerLink="/sports">Sports</button>
    <button mat-button>Grocery</button>
</mat-toolbar>
<!--app.component.html-->
<app-header></app-header>
<router-outlet></router-outlet>

Note: router-outlet acts as a placeholder that Angular dynamically fills based on the current router state.