Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse template HTML block in Angular?

Tags:

angular

Lets suppose we have html block in file:

<div id="text">Text</div>

How can I reuse this html code below in the same file, I mean something like this:

<re-use id="text"></re-use>

Is it possible?

like image 710
OPV Avatar asked Jun 28 '18 15:06

OPV


People also ask

What is ngTemplateOutlet in Angular?

ngTemplateOutlet is a structural directive. We use it to insert a template (created by ngTemplate ) in various sections of our DOM. For example, you can define a few templates to display an item and use them display at several places in the View and also swap that template as per the user's choice.

How do templates work in Angular?

A template is a form of HTML that tells Angular how to render the component. Views are typically organized hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's host view.


2 Answers

I think you wanted to reuse the same html block again. If i understand you correctly, below code should help

<ng-template #MsgRef >
        {{ mycontent }}
</ng-template>

To reuse above block in the same template,

 <ng-template [ngTemplateOutlet]="MsgRef"></ng-template> //reuse any number of times
like image 98
Ramya S Avatar answered Oct 19 '22 07:10

Ramya S


Creating a new component is the most common way, but sometimes you only need some local markup to be repeated and ng-template allows that.

What is interesting is that it's even possible to pass a context to be able to use data binding:

<ng-template #tplPerson let-person>
    <span class="person-id">{{person.id}}</span>
    <span class="person-alias" *ngIf="!!person.alias">"{{person.alias}}"</span>
    <span class="person-name">{{person.name}}</span>
</ng-template>

let-person without a value defines the context variable person with the value set to $implicit when instantiating the template:

<ng-template *ngTemplateOutlet="tplPerson; context: {$implicit: thePerson}"></ng-template>

See more options in the documentation of NgTemplateOutlet.

like image 72
Mart Avatar answered Oct 19 '22 05:10

Mart