问题
Is it possible to insert a component into another parent component and pass data to the child component from the parent component?
- User Component
- Table Component
- Detail Component
in user.html
<app-table>
<app-detail></app-detail>
</app-table>
in table.html
<div *ngFor="let item of items">
<ng-content [item]="item"></ng-content> (its my problem)
</div>
回答1:
You can use ngTemplateOutlet
:
https://angular.io/api/common/NgTemplateOutlet
<app-user>
<app-table [cardTemplate]="pCard"></app-detail>
</app-user>
<ng-template let-record #pCard>
<div class="card">
</div>
</ng-template>
Table component:
<div class="nsCard">
<ng-container *ngTemplateOutlet="cardTemplate; context:{$implicit: record}"></ng-container>
</div>
And inside table component:
@Input() cardTemplate: TemplateRef<any>;
Actually it is more advanced form of ng-template
, that provides ability to pass data and many others.
来源:https://stackoverflow.com/questions/58292748/insert-a-component-into-another-parent-component-and-pass-data