Friday, February 16, 2018

Working with template in Angular 2

Here is the way by which we can work with template and assign template dynamically as well.

(1) First import statement
import { Component, ViewChild, TemplateRef } from '@angular/core';
notice here we have included ViewChild & TemplateRef as well and it is used for the same purpose to bind it with template

(2) Declare your component
@Component({
    ....// Place your component stuff here
})

(3) Declare your class
- first, declare your class then add below line of code for template
@ViewChild('template1') template1: TemplateRef;
@ViewChild('template2') template2: TemplateRef;

- add below function also
getTemplate(templatename) {
        return templatename == "template1" ? this.template1 : this.template2;
    }

- over here i am assuming there is an array of items you have and you are iterating by each item to bind that item data with template

(4) Now, at your html area
<table>
    <thead>        
        <th></th>
    </thead>
    <tbody>
        <tr *ngFor="let item of arrayitem; let i = index">
            <ng-template [ngTemplateOutlet]="getTemplate('template1')" 
            [ngOutletContext]="{ $implicit: item, index: i }"></ng-template>
        </tr>
    </tbody>
</table>
<ng-template #template1 let-item>
    //template1 html
</ng-template>
<ng-template #template2 let-item>
    //template2 html
</ng-template>

- ng-template - in ng-template, we are getting template to be used by calling method "getTemplate" and passing parameter "template1" to "ngTemplateOutlet" property. In this iteration it will get "template1" template and bind html in it with specified item

(5) currently, i have passed "template1" in "getTemplate" method to get template, but we can make it variable and based on assigned value to that variable appropriate template can be bind runtime. 


No comments:

Post a Comment