Welcome to the Angular Tutorial on the @Input Decorator! In this lesson, we'll explore one of the most powerful features in Angular that allows parent components to communicate with child components. Let's get started! 📝
@Input 💡Before diving into the @Input decorator, let's discuss the importance of communication between components. Imagine building a complex application where multiple components are interconnected, and data needs to be shared between them. To achieve this, Angular provides the @Input decorator.
@Input Decorator? 💡The @Input decorator is used to define an input property of a child component, which can receive data from its parent component. It enables a child component to accept data from its parent, making the communication bidirectional.
@Input Decorator 📝To create an input property, simply add the @Input() decorator before the property name in the child component's TypeScript file.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() dataFromParent: string;
}In the above example, we have defined an input property called dataFromParent in the ChildComponent.
To pass data to the child component, we use the dataFromParent property in the parent component's HTML file and bind it to the corresponding child component.
<app-child [dataFromParent]="someData"></app-child>Here, someData is a property in the parent component that holds the data to be passed to the child component.
Let's create a simple example where a parent component passes a title to a child component and displays it.
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
title = 'Hello, Child Component!';
}import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h2>Title from Parent Component: {{ dataFromParent }}</h2>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() dataFromParent: string;
}<app-child [dataFromParent]="title"></app-child>Run the application, and you'll see the title "Hello, Child Component!" displayed on the child component, which was passed from the parent component.
What does the `@Input()` decorator do in Angular?
That's it for this tutorial on the @Input decorator in Angular! In the next lesson, we'll explore the @Output decorator, which enables child components to send events to their parents.
Happy coding! 🎉