1) Required Component Input from Angular 16.
Now a component can have a required Input.
Imagine we have a component with an input called user and we want it to be mandatory, meaning it should always be present. To do this, we open and close curly brackets and set required to true:
By doing this, an error will appear if we try to use this component without passing its mandatory input. If we pass the input, it runs correctly:
This simplifies development, especially in older projects, as it will be easy to detect which inputs are mandatory and which are not. In previous versions, you could only add validations to check if inputs existed.
2) Input Transformations in Components in Angular 16.
An input is used to pass information from a parent component to a child component. But sometimes we want to pass the information in a different way or format. From this version onward, we can transform our inputs very easily.
Imagine we have a component with an input called stock. We want that when the stock is null, instead of appearing as null, it shows 0. In other words, we want to make a small transformation.
<app-available-stock [stock]="null" />
In the past, we could only do this with a setter, but it was cumbersome as we had to create a setter and then a separate variable to display the data:
Now, within an input, we can set the transform property and use a function to handle the transformation:
Now, the transformation happens inside the object brackets within the input. We set transform and pass a function to it. For the example, we declare the transformation function above, but in practice, we can create a file or something similar. In the component’s HTML, we directly call the stock variable: {{stock}}
3) Extract URL Parameters Using Inputs, Without ActivatedRoute, in Angular 16.
Before, the only way we had to obtain a route parameter was with ActivatedRoute. In the example, the parameter is called id, and the service is injected and used:
However, now we can also do this with inputs, simply by creating an input that has the same name as the route parameter, and its property is retrieved. To make this work, we need to have it configured in the provideRouter in appConfig: withComponentInputBinding()
:
This new approach avoids the need to inject the service.
— Notes based on the Angular course from EfisioDev —
Top comments (1)
Hi Samira Awad,
Top, very nice and helpful !
Thanks for sharing.