Angular @Input - Sharing Data Between Components in Angular: A Simple Guide
What is @Input in Angular?
Imagine you’re building a LEGO set. You have different LEGO pieces (components) that need to work together to create something cool. Sometimes, one piece (a component) needs some information from another piece to do its job right. In Angular, @Input is like a connector that lets you pass that information between the pieces.
Why Do We Need @Input?
Think of a family where the parent has some important information, like dinner plans, and the kids need to know about it. @Input helps the parent component (like the parent in the family) share that information with the child component (like the kids).
How Does @Input Work?
Let’s break it down step by step, just like building a LEGO set:
ng generate component child
2. Set Up the Child Component: This is where you tell the child component, “Hey, you’re going to get some data from the parent!” You do this by adding @Input to a property in the child component’s code.
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ childData }}</p>',
})
export class ChildComponent {
@Input() childData: string;
}
Here, childData is like a mailbox where the child component will receive the information.
3.Pass Data from Parent to Child: Now, the parent component needs to send some data to the child. This is done in the parent’s template (HTML file), where you tell the child component what data to use.
<!-- parent.component.html -->
<app-child [childData]="parentData"></app-child>
In the parent’s code, you define what parentData is.
领英推荐
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
parentData = 'Hello from Parent!';
}
Putting It All Together
Here’s the full picture:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
parentData = 'Hello from Parent!';
}
2. Parent Component Template (parent.component.html):
<app-child [childData]="parentData"></app-child>
3. Child Component Code (child.component.ts):
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ childData }}</p>',
})
export class ChildComponent {
@Input() childData: string;
}
What Happens?
So when you run your Angular app, the child component will show “Hello from Parent!” because that’s what the parent component sent over.
In Simple Terms
I hope this explanation helps you understand how @Input works in a more relatable way!