Angular 16 | Reading Route Parameters with Input() in an Explicit Way

One of the changes that Angular brought in its latest version was the possibility to get route data using the@Input() decorator. However, this generated a discussion in the community:
Can there be confusion about the purpose of @Input?
Next, we will understand the functionality and apply a change that will make the visibility of Input’s of the Router clearer.
Enabling the use of @Input in the Router
To use the functionality, we need to change the Router by adding the withComponentInputBinding()
function for standalone applications or the bindToComponentInputs
property for modules:
const routes: Routes = [{ path: 'page/:id', component: PageComponent, }, ];
bootstrapApplication(App, {
providers: [provideRouter(routes, withComponentInputBinding())],
});
@NgModule({
imports: [
RouterModule.forRoot(routes, {
bindToComponentInputs: true
})
],
})
export class AppModule {}
Getting parameters
From this point, we can already get the id
of the route page/:id
in the PageComponent
through the @Input
:
@Component({
// ...
template: `<div>Page id = {{id}}</div>`,
})
export class PageComponent {
// Acessando rota /page/1 aplica valor "1" ao id.
@Input() id: string = '';
}
However, when viewing the code above without the comment, we cannot say for sure if this @Input
is from a route or is passed through a parent component.
The trick ⚡️
To make it clear what the purpose of the @Input
is without having to add comments, we can use the aliases @RouteParam
and @RouteQueryParam
:
import {
Component,
Input as RouteParam, // Para parâmetros /page/:id
Input as RouteQueryParam, // Para queryStrings /page/:id?name=home
} from '@angular/core';
@Component({
// ...
template: `<div>Page id = {{id}}</div>`,
})
export class PageComponent {
@RouteParam() id: string = '';
@RouteQueryParam() name: string = '';
}
This way, whenever we view the code, we can understand the data source of the property.
Example of use in StackBlitz:
@RouteParam
and @RouteQueryParam
Conclusion
The discussion raised is valid and I agree that there may be confusion about the use of @Input
. The form presented comes to make it more perceptible what the decorator is actually doing. This way, we make the code clearer.