Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a template to child component in angular 6

Tags:

angular

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>
like image 781
Seven Avatar asked Aug 22 '18 17:08

Seven


People also ask

What are templates in Angular 6?

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.

How do you style a child component from the parent component?

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.

Where do you put ng templates?

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.


1 Answers

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

like image 192
Vlad274 Avatar answered Sep 27 '22 20:09

Vlad274