Binding Route Data to Component Inputs in Angular v16
Traditionally, properties marked with the @Input decorator have been understood as bindings to DOM properties, enabling parent-to-child communication. For example, when a child component defines an input property named name, it can be utilized in the following manner:
<app-child name="John"></app-child>
With Angular version 16, a new capability emerges: inputs can now be declared to bind directly to route parameters.
To illustrate, imagine the following route configuration:
const routes: Routes = [
{
path: 'hero/:id',
component: ChildComponent,
},
];
Previously, retrieving the ID within the component—say, to fetch a hero by that identifier—required code like this:
export class ChildComponent {
constructor(route: ActivatedRoute) {
route.params.subscribe((params) => console.log(params.id));
}
}
Now, this is achieved simply by utilizing @Input. The process is straightforward, as shown here:
export class ChildComponent {
@Input() id: string;
}
But there's more! The scope of accessible data extends beyond just route parameters to include:
- route parameters
- query parameters
- data from the
dataproperty of the route - data provided by resolvers
Let’s examine these other options, beginning with this route setup:
const routes: Routes = [
{
path: 'hero/:id',
component: ChildComponent,
resolve: {
heroName: () => 'Yoda',
},
data: {
heroPower: 'Force',
},
},
];
Here, we have:
idas a route parameterheroNameas data supplied by a resolverheroPoweras data taken from thedataproperty
Within the component, we can declare input properties for each of these items, plus an additional one for a query parameter, in this manner:
export class ChildComponent {
@Input() id?: string;
@Input() heroName?: string;
@Input() heroPower?: string;
@Input() heroParameter?: string;
}
And that's it! The system functions seamlessly, with inputs automatically reflecting current route parameters—all without the necessity of injecting ActivatedRoute into the component.
Enjoy exploring these new Angular 16 features! ?
