Dynamic components trong Angular là gì?
Dynamic components trong Angular là gì?
Dynamic component là component được tạo lúc chạy (runtime) bằng code, thay vì được khai báo sẵn trong template. Dùng khi chỉ biết component nào cần hiển thị lúc ứng dụng chạy: hộp thoại (dialog), thông báo (toast), widget của dashboard theo cấu hình từ server, form sinh từ schema, plugin.
ngComponentOutlet (đơn giản, khai báo trong template)@Component({
selector: 'app-dashboard',
imports: [NgComponentOutlet],
template: `
@for (w of widgets(); track w.id) {
<ng-container *ngComponentOutlet="w.component; inputs: w.inputs" />
}
`,
})
export class DashboardComponent {
widgets = signal([
{ id: 1, component: ChartWidget, inputs: { title: 'Doanh thu' } },
{ id: 2, component: TableWidget, inputs: { pageSize: 10 } },
]);
}
ViewContainerRef.createComponent (kiểm soát bằng code)@Component({
selector: 'app-host',
template: `<ng-container #host />`,
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.