Angular: the Input decorator

Angular: the Input decorator

In this article, we will explore how to use the @Input decorator to pass data from a parent component to a child component in Angular.

Angular is a powerful front-end development framework that allows the creation of dynamic and complex web applications. Among its many features, the @Input decorator plays a crucial role in communication between components. In this article, we will explore how to use the @Input decorator to pass data from a parent component to a child component in Angular.

The @Input decorator is an essential tool in Angular that allows you to pass data from a parent component to a child component. This decorator is used to declare a property within a child component, allowing it to receive data from the parent component.

Make sure to import the @Input decorator from the '@angular/core' package into your TypeScript file. The import should look like this:


import { Input } from '@angular/core';

Within the child component, declare a variable with the @Input decorator. For example:


@Input() inputData: string;

Here, inputData is the property that the child component can use to receive data from the parent component.

In the parent component template, use binding syntax to pass data to the child component. For example:


<app-child-component [inputData]="datiDaPassare"></app-child-component>

Now, in the child component, you can use the inputData variable like any other local variable. For example:


// In the child component
console.log(this.inputData);

Advantages

  • Communication between components: Allows easy communication between parent and child components.
  • Component reuse: Makes components more flexible and reusable, as they can receive external data to adapt to different contexts.

Conclusions

The @Input decorator in Angular is a powerful tool for facilitating communication between components. By allowing data to be passed from a parent component to a child component, it provides greater flexibility and modularity in Angular applications. Knowing how to use this decorator correctly is essential for developing efficient and maintainable web applications.