I am looking for a way to repeat the same markup on multiple spots in my component. I know I could just use a new component but im looking for something a little less serious.
The html
<nav class="pages">
<ul class="inline">
<li
*ngFor="let p of pages; let i = index;"
[ngClass]="{'active': page.current_page == i+1}"
(click)="onPageChange(i+1, $event)"
>{{i+1}}</li>
</ul>
</nav>
Is there a way to use ng-template
to repeat this same mark up in multiple places within the same component... Something like below
<div id="header"> <ng-template [innHTML]="#pages"></ng-template> </div>
<div id="content">...</div>
<div id="footer"> <ng-template [innHTML]="#pages"></ng-template> </div>
<ng-container #pages>
<ul class="inline">
<li *ngFor="let p of pages; let i = index;" [ngClass]="{'active': page.current_page == i+1}" (click)="onPageChange(i+1, $event)">{{i+1}}</li>
</ul>
</ng-container>
You can insert the content of an ng-template
with ng-container
Angular elements and the ngTemplateOutlet directive.
<div id="header">
<ng-container *ngTemplateOutlet="pages; context: { text: 'value1' }"></ng-container>
</div>
<div id="content">...</div>
<div id="footer">
<ng-container *ngTemplateOutlet="pages; context: { text: 'value2' }"></ng-container>
</div>
<ng-template #pages let-value="text">
<div>The value is {{value}}</div>
<ul class="inline">
<li *ngFor="let p of pages; let i = index;" [ngClass]="{'active': page.current_page == i+1}" (click)="onPageChange(i+1, $event)">{{i+1}}</li>
</ul>
</ng-template>
Create a child component containing your html in it's template and use it as many times you need in your (parent) component, like so:
Child component:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child-comp',
template: `
<nav class="pages">
<ul class="inline">
<li
*ngFor="let p of pages; let i = index;"
[ngClass]="{'active': page.current_page == i+1}"
(click)="onPageChange(i+1, $event)"
>{{i+1}}</li>
</ul>
</nav>
`,
styleUrls: ['./child-comp.component.css']
})
export class ChildCompComponent implements OnInit {
@Input() pages;
constructor() { }
ngOnInit() {
}
onPageChange(index, event) {
}
}
Parent Component:
<div id="header">
<app-child-comp [pages]="pages"></app-child-comp>
</div>
<div id="content">...</div>
<div id="footer">
<app-child-comp [pages]="pages"></app-child-comp>
</div>