背景關系:-作為 AWS S3 存盤桶中的靜態資產獨立部署的小型 Angular 應用程式(單個螢屏上只有兩個選項卡)。
鑒于:- 我的一個 Angular(12) 容器組件有很長的標記,但由于創建網格,大部分代碼都重復了,我在一行中有幾列,如下所示
<div class="col">
<div class="row">
<div class="col">{{aStringTitle}}</div>
</div>
<div class="row">
<div class="col mt-2">
{{differentMarkupForEachColumn}}
</div>
</div>
</div>
我想要實作的目標:- 我想使用*ngFor傳遞以下型別的陣列來呈現這些列:-
[
{name: 'First Ng Component', component: <SmallAngularComponent>},
{name: 'Second Ng Component', component: <AnotherSmallAngularComponent>},
...... and so on upto 7-8 smaller angular components
]
當我檢查 angular.io 時,我在模板檔案中找不到合適的示例。
實際問題:-如何將一組 Angular 組件傳遞給包含 Angular 組件的模板?
我不想要的:- 在這個答案中解釋了替代方法,但我想呈現正確的 Angular 組件而不是一些隨機的 html。
uj5u.com熱心網友回復:
因此,如果我理解正確的話,您希望在 HTML 中動態創建這些組件。
為此,您可以簡單地使用NgComponentOutlet(請參閱此處了解更多資訊)。
您的代碼如下所示:
組件.ts
components = [
{ name: 'First Ng Component', component: SmallAngularComponent },
{ name: 'Second Ng Component', component: AnotherSmallAngularComponent },
// ...... and so on upto 7-8 smaller angular components
];
您可能已經注意到您不需要<>這些組件。
組件.html
<ng-container *ngFor="let entry of components">
<div class="col">
<div class="row">
<div class="col">{{ entry.name }}</div>
</div>
<div class="row">
<div class="col mt-2">
<ng-container *ngComponentOutlet="entry.component"></ng-container>
</div>
</div>
</div>
</ng-container>
如果您需要將引數傳遞給不同的組件,您可以查看此處,或者您需要以編程方式創建這些組件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403099.html
標籤:
上一篇:聯合事件處理程式型別
