Angular Component Communication: Input, Output และ ViewChild อธิบายแบบเข้าใจง่าย
#angular12 เม.ย. 2569
Angular Component Communication คืออะไร
ใน Angular การสื่อสารระหว่าง Component เป็นสิ่งสำคัญมาก เพราะ application จริงมักประกอบด้วย component หลายตัวที่ต้องส่งข้อมูลหากัน
3 วิธีหลักในการส่งข้อมูลระหว่าง Component
1. @Input() — Parent ส่งข้อมูลไป Child
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>Hello, {{ name }}!</p>`
})
export class ChildComponent {
@Input() name: string = '';
}
<!-- parent.component.html -->
<app-child [name]="username"></app-child>
2. @Output() + EventEmitter — Child ส่งข้อมูลกลับ Parent
// child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="sendData()">Send</button>`
})
export class ChildComponent {
@Output() dataEvent = new EventEmitter<string>();
sendData() {
this.dataEvent.emit('Hello from child!');
}
}
<!-- parent.component.html -->
<app-child (dataEvent)="onReceive($event)"></app-child>
3. @ViewChild() — Parent เข้าถึง Child โดยตรง
// parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `<app-child></app-child>`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child.name);
}
}
เลือกใช้วิธีไหนดี?
| วิธี | ใช้เมื่อ |
|---|---|
| @Input() | Parent ต้องการส่งข้อมูลลงไปหา Child |
| @Output() | Child ต้องการแจ้ง Parent ว่ามีเหตุการณ์เกิดขึ้น |
| @ViewChild() | Parent ต้องการเรียกใช้ method หรืออ่าน property ของ Child โดยตรง |
สรุป
การเข้าใจ Component Communication เป็นพื้นฐานสำคัญของ Angular ทุก developer ควรเข้าใจทั้ง 3 วิธีนี้ก่อนเริ่มสร้าง application จริงครับ