我正在寻找在组件中多个位置重复相同标记的方法。我知道我可以使用一个新组件,但是我正在寻找不太严重的东西。
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>
有没有一种方法可以使用ng-template
在同一组件中的多个位置重复进行相同的标记...如下所示
<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>
答案 0 :(得分:2)
您可以插入带有ng-template
Angular元素和ngTemplateOutlet指令的ng-container
的内容。
<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>
答案 1 :(得分:0)
创建一个在模板中包含html的子组件,并根据需要在(父)组件中多次使用它,如下所示:
子组件:
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) {
}
}
父项:
<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>