DEV Community

Sanjai Sakthivel
Sanjai Sakthivel

Posted on

RouterInput in Angular v16

Introduction:

Angular v16 has recently been released, bringing along a range of new features aimed at enhancing the developer experience. One of these exciting features is RouterInput, which allows developers to retrieve route information through inputs. In this blog post, we will explore how RouterInput can be utilized and discuss its benefits.

What is RouterInput?

RouterInput is a new API introduced in Angular v16 that enables developers to listen to route parameters through input bindings in their components. This means that when a route parameter changes, the component is notified through an observable stream, allowing for dynamic updates.

Getting Started with RouterInput:

To start using RouterInput, you need to update your route provider in the main.ts file. This can be done by importing the necessary modules and adding the "withComponentInputBinding()" method to your route provider configuration. Here's an example:

import { provideRouter, withComponentInputBinding } from '@angular/router';

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(appRoutes, withComponentInputBinding())
  ]
});
Enter fullscreen mode Exit fullscreen mode

Once the route provider is updated, you can start utilizing RouterInput in your components. Simply add the "@Input()" decorator to the properties that you want to bind to route parameters. Here's an example:

`@Input() testId!: string;
@Input() permission!: string;
@Input() user!: string;`
Enter fullscreen mode Exit fullscreen mode

With these input bindings, your component will be notified whenever the corresponding route parameters change.

Additional Notes on RouterInput:

  1. Router Inputs are only accessible within the routed component. If you need to access these parameters within a child component, you can either pass the input through input binding between the parent and child components or use other methods mentioned earlier.
  2. If you prefer a more descriptive decorator name for RouterInput, you can remap it in its definition using the "import {Input as RouterInput} from '@angular/core'" statement. This allows you to use the new decorator name in your component.

Conclusion:

RouterInput is a valuable addition to Angular v16, providing developers with a convenient way to retrieve and react to route parameters through input bindings. By incorporating RouterInput into your Angular projects, you can enhance the flexibility and responsiveness of your components. So, go ahead and explore this new feature to further improve your Angular development experience.

Happy coding!

Top comments (0)