In this case, the app-child can not be changed, which means you can only operate the app-parent. My opinion is finding a way to insert the template in app-child, is there a function which like Renderer2.insert(parent, newItem, childRef)
or another solution ?
Look at https://stackblitz.com/edit/insert-template-to-child-component for detail.
app.component.html
<app-parent>
<ng-template #childTemplate>
how to insert this template in app-child
</ng-template>
</app-parent>
parent.component.html
<app-child>
<!-- <ng-template #childTemplate>
this is work, but I need to input the template in app-parent content
</ng-template> -->
</app-child>
child.component.html
<ng-container [ngTemplateOutlet]="childTemplate"></ng-container>
Angular 6 uses the <ng-template> as the tag similar to Angular 4 instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead.
use @Component to add css class to host element and set encapsulation to none. Then reference that class which was added to the host within the components style. css. scss This will allow us to declare styles which will only affect ourselves and our children within scope of our class.
ng-template should be used along with structural directives like [ngIf],[ngFor],[NgSwitch] or custom structural directives. That is why in the above example the contents of ng-template are not displayed. ng-template never meant to be used like other HTML elements.
You can pass the template as an @Input()
to the child
parent.component.html
<ng-template #childTemplate></ng-template>
<app-child [childTemplate]="childTemplate"></app-child>
child.component.ts
@Input()
childTemplate: TemplateRef<any>;
child.component.html
<ng-container [ngTemplateOutlet]="childTemplate"></ng-container>
You can use this same strategy to pass the template down multiple levels if needed.
More detailed information: https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/#configurablecomponentswithtemplatepartialinputs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With