Component gồm lớp TypeScript, template và style. Bài này tạo component bằng CLI, truyền dữ liệu bằng input(), phát sự kiện bằng output() và lồng component.
Bạn sẽ học được
- Tạo component bằng ng generate
- Hiểu decorator @Component
- Truyền dữ liệu bằng input()
- Phát sự kiện bằng output()
Tạo component
ng generate component the-sinh-vien
# viết tắt: ng g c the-sinh-vienInput và output
// the-sinh-vien.ts
import { Component, input, output } from "@angular/core";
@Component({
selector: "app-the-sinh-vien",
template: `
<div class="the">{{ sv().ten }} - {{ sv().diem }}
<button (click)="xoa.emit(sv().ma)">Xóa</button>
</div>`,
styles: ".the { padding: 8px; border: 1px solid #ddd; }"
})
export class TheSinhVien {
sv = input.required<{ ma: string; ten: string; diem: number }>();
xoa = output<string>();
}// app.ts: imports: [TheSinhVien]
<app-the-sinh-vien [sv]="s" (xoa)="xoaSV($event)" />Ghi chú
selectorlà tên thẻ dùng trong template khác.- Component standalone khai báo các component con trong mảng
imports. - Bản cũ dùng
@Input(),@Output()và EventEmitter; cách mới input(), output() trả về signal.
Thực hành
- Tạo component TheSinhVien nhận dữ liệu qua input.
- Phát sự kiện xóa lên component cha.
- Hiển thị 3 thẻ sinh viên trong App.
Tóm tắt bài học
- Component = lớp + template + style.
- input() nhận dữ liệu, output() phát sự kiện.
- Khai báo component con trong imports.

