# Angular Routing --- #### Motivation ```angular181html @switch (state) { @case (login) {
} @case (shop) {
} @case (product-details) {
} @case (user-details) {
} @case (admin) { @if (isAdmin(user)) {
} } @default {
``` * 😕 * Back-Button ⚠️ --- #### Setup ```typescript export const appConfig: ApplicationConfig = { providers: [provideRouter(routes, withComponentInputBinding()),] }; ``` ```typescript const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'shop', component: ShopComponent } ]; ``` ```angular181html
Login
Shop
Search
``` ---- #### Active link styling ```
Login
Shop
```
css-Klasse
active
, falls aktuelle Route
/login
--- #### Routing mit input ```typescript const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'shop', component: ShopComponent }, { path: 'products/:id', component: ProductComponent } ]; ``` ```typescript export class ProductComponent implements OnInit{ id = input.required
(); constructor() { // input not yet available } ngOnInit() { console.log(this.id()); } } ``` ---- #### Wildcard Routes ```typescript const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'shop', component: ShopComponent }, { path: 'products/:id', component: ProductComponent }, { path: '**', component: PageNotFoundComponent } ]; ```
paths werden nach Reihenfolge versucht
⚠️
muss letzte sein
⚠️
---- #### Redirects ```typescript const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'shop', component: ShopComponent }, { path: 'products/:id', component: ProductComponent }, { path: '', redirectTo: '/login', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; ``` auch als Funktion möglich ```typescript { path: 'logout', redirectTo: ({ queryParams }) => { if (condition) return '/login'; else return '/shop'; } } ``` --- #### Routing aus ts ```typescript export class ShopComponent { constructor(private router:Router, private route: ActivatedRoute) { } navigation() { // /products/angular/42 this.router.navigate(['/products','angular',42]); // /products/42 this.router.navigate(['/products', { id: 42 }]); // /search?q=angular this.router.navigate(['/search', { queryParams: { q: 'angular' } }]); // /shop/basket this.router.navigate(['basket'], { relativeTo: this.route }); } } ``` --- #### Route Guards ```typescript { path: 'admin', component: AdminComponent, canActivate: [authGuard] } ``` ```typescript export const authGuard: CanActivateFn = ( next: ActivatedRouteSnapshot, state: RouterStateSnapshot ) => { const authService = inject(AuthService); // DI const router = inject(Router); if (authService.isLoggedIn()) { return true; } else { router.navigate(['/login']); return false; } } ``` canDeactivate äquivalent