30秒学会 Angular 片段 · 2019年5月12日

30秒学会 Angular 片段 – Reusing code in template

While the best way of reusing your code is creating a component, it’s also possible to do it in a template.

To do this you can use ng-template along with *ngTemplateOutlet directive.

<p>
  <ng-container *ngTemplateOutlet="fancyGreeting"></ng-container>
</p>

<button>
  <ng-container *ngTemplateOutlet="fancyGreeting"></ng-container>    
</button>

<ng-template #fancyGreeting>
  Hello <b>{{name}}!</b>
</ng-template>

file:app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <p>
      <ng-container *ngTemplateOutlet="fancyGreeting"></ng-container>
    </p>

    <button>
      <ng-container *ngTemplateOutlet="fancyGreeting"></ng-container>    
    </button>

    <ng-template #fancyGreeting>
      Hello <b>{{name}}!</b>
    </ng-template>
  `,
})
export class AppComponent  {
  name = 'Angular';
}

翻译自:https://www.30secondsofcode.org/angular/s/reusing-code-in-template

相关链接