[Angular] Change component default template (ng-content, ng-template, ngTemplateOutlet, TemplateRef)

Here is the defulat tab header template:

<ng-template #defaultTabHeader let-tabs="tabsX">
  <ul class="tab-panel-buttons" *ngIf="tabs">
    <li
      [ngClass]="{selected: tab.selected}"
      (click)="selectTab(tab)"
      *ngFor="let tab of tabs;">{{tab.title}}
    </li>
  </ul>
</ng-template>

<ng-content
  *ngTemplateOutlet="defaultTabHeader; context: tabsContext"></ng-content>

<ng-content></ng-content>

we have set up that we can switch the default template when we pass in another template.

Now, what we want is able to pass in a custom template to replace the default header.

  <ng-template #headerButtons>
    <button>Login</button>
    <button>Sign up</button>
  </ng-template>

This is the new template, we want to replace the default header.

Now we pass this to the component:

  <ng-template #headerButtons>
    <button>Login</button>
    <button>Sign up</button>
  </ng-template>

    <au-tab-panel [headerTemplate]="headerButtons">

Create a 'headerTemplate' Input on the component, and pass in the template ref.

export class AuTabPanelComponent implements OnInit, AfterContentInit {

  @Input()
  headerTemplate: TemplateRef<any>;

Now we need to check whether the custom template passed in or not, if passed in then we use custom template, otherwise the default template.

<ng-template #defaultTabHeader let-tabs="tabsX">
  <ul class="tab-panel-buttons" *ngIf="tabs">
    <li
      [ngClass]="{selected: tab.selected}"
      (click)="selectTab(tab)"
      *ngFor="let tab of tabs;">{{tab.title}}
    </li>
  </ul>
</ng-template>

<ng-content
  *ngTemplateOutlet="headerTemplate ? headerTemplate :defaultTabHeader; context: tabsContext"></ng-content>

Now we need to export the 'au-tab-panel' component's method to the custom template, to do that we can use template ref:

  <ng-template #headerButtons>
    <button (click)="tabPanel.selectTab(loginTab)">Login</button>
    <button (click)="tabPanel.selectTab(signUpTab)">Sign up</button>
  </ng-template>

    <au-tab-panel #tabPanel [headerTemplate]="headerButtons">

      <au-tab title="login" #loginTab>
        <form>
          <div class="form-field">
            <label>Email:</label><input>
          </div>
          <div class="form-field">
            <label>Password:</label><input>
          </div>
        </form>
      </au-tab>

      <au-tab title="Sign up" #signUpTab>
        <form>
          <div class="form-field">
            <label>Email:</label><input>
          </div>
          <div class="form-field">
            <label>Password:</label><input>
          </div>
          <div class="form-field">
            <label>Confirm Password:</label><input>
          </div>
        </form>
      </au-tab>
原文地址:https://www.cnblogs.com/Answer1215/p/7052147.html