repeat html within the same component

陌路散爱 提交于 2019-12-25 03:23:01

问题


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>

回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/53504414/repeat-html-within-the-same-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!