[Angular] Learn How To Use ng-template Inputs

For example, we have a modal component, it can config that using ng-template as a configurable template. 

<ng-template #auModalBody></ng-template>

<au-modal [body]="auModalBody" ></au-modal>

 

Now what we want to do is to pass in inputs to ng-templates so that template can change dynamiclly according to the inputs.

For example:

<ng-template #auModalBody
      let-title="title"  <!-- define a title prop -->
      let-tabActivated=loginTabActivated <!-- define a tabActivated prop -->
>
   <!-- we can use 'title' & 'tabActivated' props here -->
   <h2>{{title}}</h2>
   <tab [selected]="tabActivated" #login />
   <tab [selected]="!tabActivated" #signUp />
</ng-template>

<au-modal [body]="auModalBody" [context]="{
  title: 'Login or Sign up',
  tabActivated: loginTabActivated  <!-- based on those variables we passed in-->
}"></au-modal>    

 

To do that, we need to add an @Input to au-modal component:

@Input() context: any;


    <ng-container *ngIf="body; else projectionBody">
      <ng-container *ngTemplateOutlet="body; context:context" ></ng-container>
    </ng-container>

 

See the commit: Github

posted @ 2017-07-02 20:14  Zhentiw  阅读(238)  评论(0编辑  收藏  举报