Common routing tasks • Angular

.pdf
School
Northeastern University**We aren't endorsed by this school
Course
INFO 6255
Subject
Computer Science
Date
Dec 22, 2024
Pages
7
Uploaded by UltraLapwingPerson47
A well-functioning application should gracefully handle when users attempt to navigateto a part of your application that does not exist. To add this functionality to yourapplication, you set up a wildcard route. The Angular router selects this route any timethe requested URL doesn't match any router paths.To set up a wildcard route, add the following code to your definition.The two asterisks, , indicate to Angular that this definition is a wildcardroute. For the component property, you can define any component in your application.Common choices include an application-specific , which youcan define to to your users; or a redirect to your application's maincomponent. A wildcard route is the last route because it matches any URL. For moredetail on why order matters for routes, see .To display a 404 page, set up a with the property set to thecomponent you'd like to use for your 404 page as follows:{ path: '**', component: <component-name> }constroutes:Routes=[{ path: 'first-component', component: FirstComponent },{ path: 'second-component', component: SecondComponent },{ path: '**', component: PageNotFoundComponent }, // Wildcard ro];
Background image
The last route with the of is a wildcard route. The router selects this route ifthe requested URL doesn't match any of the paths earlier in the list and sends the userto the .To set up a redirect, configure a route with the you want to redirect from, theyou want to redirect to, and a value that tells the router howto match the URL.In this example, the third route is a redirect so that the router defaults to theroute. Notice that this redirect precedes the wildcard route. Here,means to use the initial relative URL ().Sometimes a redirect is not a simple, static redirect. The property canalso be a function with more complex logic that returns a string or .constroutes:Routes=[{ path: 'first-component', component: FirstComponent },{ path: 'second-component', component: SecondComponent },{ path: '', redirectTo: '/first-component', pathMatch: 'full'}{ path: '**', component: PageNotFoundComponent }, // Wildcard ro];constroutes:Routes=[{ path: "first-component", component: FirstComponent },{path: "old-user-page",redirectTo: ({ queryParams}) =>{
Background image
As your application grows more complex, you might want to create routes that arerelative to a component other than your root component. These types of nested routesare called child routes. This means you're adding a second to yourapp, because it is in addition to the in .In this example, there are two additional child components, , and .Here, has its own and a second inaddition to the one in .consterrorHandler=inject(ErrorHandler);constuserIdParam=queryParams['userId'];if(userIdParam !==undefined) {return`/user/${userIdParam}`;} else{errorHandler.handleError(newError('Attempted navigation toreturn`/not-found`;}},},{ path: "user/:userId", component: OtherComponent },];<h2>First Component</h2><nav><ul><li><arouterLink="child-a">Child A</a></li>
Background image
A child route is like any other route, in that it needs both a and a .The one difference is that you place child routes in a array within the parentroute.<li><arouterLink="child-b">Child B</a></li></ul></nav><router-outlet></router-outlet>constroutes:Routes=[{path: 'first-component',component: FirstComponent, // this is the component with the <rchildren: [{path: 'child-a', // child route pathcomponent: ChildAComponent, // child route component that t},{path: 'child-b',component: ChildBComponent, // another child route componen},],},];
Background image
Each page in your application should have a unique title so that they can be identified inthe browser history. The sets the document's title using the propertyfrom the config.constroutes:Routes=[{path: 'first-component',title: 'First component',component: FirstComponent, // this is the component with the <children: [{path: 'child-a', // child route pathtitle: resolvedChildATitle,component: ChildAComponent, // child route component that },{path: 'child-b',title: 'child b',component: ChildBComponent, // another child route compone},],},];constresolvedChildATitle:ResolveFn<string> =() =>Promise.resolv
Background image
You can also provide a custom title strategy by extending the .HELPFUL:The property follows the same rules as static routeand dynamic values that implement .@Injectable({providedIn: 'root'})exportclassTemplatePageTitleStrategyextendsTitleStrategy{constructor(privatereadonlytitle:Title) {super();}overrideupdateTitle(routerState:RouterStateSnapshot) {consttitle=this.buildTitle(routerState);if(title !==undefined) {this.title.setTitle(`My Application | ${title}`);}}}exportconstappConfig:ApplicationConfig={providers: [provideRouter(routes),{provide: TitleStrategy, useClass: TemplatePageTitleStrategy},]};
Background image
Relative paths let you define paths that are relative to the current URL segment. Thefollowing example shows a relative route to another component, .and are at the same level in the tree, however,the link to is situated within the , meaning thatthe router has to go up a level and then into the second directory to find the. Rather than writing out the whole path to get to, use the notation to go up a level.In addition to , use or no leading slash to specify the current level.To specify a relative route, use the property. In thecomponent class, import from the .Then use in your navigation method. After the link parameters array,which here contains , add an object with the property set to the, which is .<h2>First Component</h2><nav><ul><li><arouterLink="../second-component">Relative Route to secon</ul></nav><router-outlet></router-outlet>
Background image