Routing and navigation
Move between screens with Angular's Router and <router-outlet>. Three things differ from the web: the URL lives in memory, you navigate from tap handlers instead of links, and the views of routes you leave stay alive.
Set up the router
Import provideRouter() from @blotch/angular-lynx instead of @angular/router. ng add @blotch/angular-lynx sets this up for you.
- Give the empty path
''a route. The app always starts at/, and there's no URL bar to start anywhere else. Without an''route, the first screen is blank. provideRouter()takes the usual router features as extra arguments, such aswithComponentInputBinding().
Navigate between screens
- Use
(bindtap), notrouterLink.RouterLinklistens forclick, which Lynx elements never fire. CallRouter.navigate()ornavigateByUrl()from a tap handler instead. - Wrap navigation in
setTimeout. Navigating creates and destroys views, which can crash the app if it happens inside the tap handler. See thesetTimeoutrule. - Failed navigations don't throw.
navigate()resolves tofalse, for example for a path with no route. WatchRouter.eventsforNavigationErrorto find out why.
Go back
Use Location.back() from @angular/common:
Location.back()andLocation.forward()move through the router's in-memory history.history.back()does nothing on a device, because there's no browser history.- The Android back button isn't connected to the router yet. In an app built with
ng build --platform android, pressing it leaves the app instead of going back a screen. See Run on iOS and Android.
Read route parameters
Turn on withComponentInputBinding() to receive route parameters as inputs:
Read parameters reactively, through an input or ActivatedRoute.paramMap, rather than once in ngOnInit. /profile/1 and /profile/2 share one component instance (see Good to know).
Lazy-loaded routes
loadComponent works:
It doesn't split your code, though. The build keeps every route's code in the bundle, so nothing downloads when the user navigates.
Differences from web Angular
Good to know
AngularLynx keeps the view of every route you visit, instead of destroying it when you leave. Lynx doesn't free a destroyed view's native elements, so an app that recreated views on every navigation would run out of them (see element pool, and Renderer internals for the details). As a result:
ngOnDestroyandDestroyRef.onDestroydon't run when you leave a route, andngOnInitdoesn't run again when you come back.- Timers, subscriptions and effects keep running while a route is hidden. Pause them in
<router-outlet (detach)="…">and restart them in(attach). - Component state survives, such as signals and form values, until the app closes.
Related
- Routing API reference
- Threads: the
setTimeoutrule - Multi-page apps: separate bundles, each its own Angular app, instead of routes
- Angular routing guide
