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

Douglas M. Barcellos
2 min readJul 16, 2023

Generated by BlueWillow AI

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:

Example using aliases @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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Douglas M. Barcellos
Douglas M. Barcellos

Written by Douglas M. Barcellos

Front-End Engineer passionate about technology and programming.

No responses yet

Write a response