Understanding @Input()
in Angular 19
The @Input()
decorator in Angular 19 allows a child component to receive data from a parent component. It is commonly used to pass dynamic values, making components reusable and modular.
Step-by-Step Guide with Example
We will create a simple Angular 19 project where a parent component passes data to a child component using @Input()
.
Step 1: Create a New Angular 19 Project
Make sure you have the latest Angular CLI installed:
npm install -g @angular/cli@latest
Now, create a new Angular project:
ng new angular-input-demo
cd angular-input-demo
ng serve
Step 2: Generate a Child Component
Create a new child component that will receive data using @Input()
:
ng generate component components/user-card
This creates:
user-card.component.ts
user-card.component.html
user-card.component.scss
user-card.component.spec.ts
Step 3: Define @Input()
in the Child Component
Modify user-card.component.ts
to accept input from the parent:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-user-card',
templateUrl: './user-card.component.html',
styleUrls: ['./user-card.component.scss']
})
export class UserCardComponent {
// Define inputs to receive data from the parent component
@Input() name: string = 'Guest';
@Input() age: number = 0;
@Input() city: string = 'Unknown';
}
Step 4: Update the Child Component Template
Modify user-card.component.html
:
<div class="user-card">
<h3>User Information</h3>
<p><strong>Name:</strong> {{ name }}</p>
<p><strong>Age:</strong> {{ age }}</p>
<p><strong>City:</strong> {{ city }}</p>
</div>
Step 5: Use <app-user-card>
in the Parent Component
Modify app.component.html
:
<h2>Passing Data to Child Component</h2>
<app-user-card name="Alice" age="28" city="New York"></app-user-card>
<app-user-card name="Bob" age="35" city="Los Angeles"></app-user-card>
<app-user-card name="Charlie" age="22" city="Chicago"></app-user-card>
Step 6: Add Some Styling (Optional)
Modify user-card.component.scss
:
.user-card {
border: 1px solid #ccc;
padding: 15px;
margin: 10px;
border-radius: 8px;
text-align: left;
background-color: #f9f9f9;
}
Step 7: Run the Project
Start the Angular application:
ng serve
Open your browser at http://localhost:4200
, and you should see the user information passed from the parent component to the child component.
Key Takeaways
✅ @Input()
allows parent components to pass data to child components.
✅ Child components use @Input()
to declare properties that accept values.
✅ Parent components bind values to @Input()
properties like:
<app-user-card name="Alice"></app-user-card>
Would you like to extend this example with real dynamic data from an API or a list of users? 🚀
No comments:
Post a Comment