Components – Creation, Communication (Input/Output)
Creation Of Component
✅ Step 1: Generate Components
ng generate component parent-dashboard
ng generate component student-detail
Observe in change in File Structure
src/
└── app/
├── parent-dashboard/
│ ├── parent-dashboard.component.ts
│ └── parent-dashboard.component.html
└── student-detail/
├── student-detail.component.ts
└── student-detail.component.html
Parent → Child Communication (via @Input)
Use Case: Parent sends student data to child component.
parent-dashboard.component.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { StudentDetail } from '../student-detail/student-detail';
@Component({
selector: 'app-parent-dashboard',
imports: [FormsModule,StudentDetail],
templateUrl: './parent-dashboard.html',
styleUrl: './parent-dashboard.css'
})
export class ParentDashboard {
student = {
name: 'Balakrishna Reddy',
course: 'Angular 20',
score: 92
};
onProgressUpdate(updatedScore: number) {
this.student.score = updatedScore;
}
}
<h2>Parent Dashboard</h2>
<app-student-detail
[studentInfo]="student"
(progressUpdated)="onProgressUpdate($event)">
</app-student-detail>
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-student-detail',
imports: [FormsModule],
templateUrl: './student-detail.html',
styleUrl: './student-detail.css'
})
export class StudentDetail {
@Input() studentInfo: any;
@Output() progressUpdated = new EventEmitter<number>();
updateProgress() {
const newScore = this.studentInfo.score + 5;
this.progressUpdated.emit(newScore);
}
}
student-detail.component.html
<p>student-detail works!</p>
<h3>Student Detail Component</h3>
<p><strong>Name:</strong> {{ studentInfo.name }}</p>
<p><strong>Course:</strong> {{ studentInfo.course }}</p>
<p><strong>Score:</strong> {{ studentInfo.score }}</p>
<button (click)="updateProgress()">Update Score</button>
src/
├── app/
│ ├── app.component.ts
│ ├── app.component.html
│ ├── parent-dashboard/
│ │ └── parent-dashboard.component.ts
│ └── student-detail/
│ └── student-detail.component.ts
app.component.html
<!-- ✅ Render Parent Component -->
<app-parent-dashboard></app-parent-dashboard>
<!-- ✅ Optional: Render Student Component directly -->
<app-student-detail [studentInfo]="{name: 'Aarav', course: 'Angular 20', score: 88}"></app-student-detail>
Comments
Post a Comment