0

Sometimes I want to reuse some views (HTML code) in a component (but won't create new component). Somethings like this:

<div *ngIf="Fordestop">
    <div class="divdesktop"></div>
    #insert-my-reuse-div-here
</div>

<div *ngIf="ForMobile">
    <div class="divmobile"></div>
    #insert-my-reuse-div-here
</div>

<ng-template #my-reuse-div>
<!--My reuse view-->
</ng-template>

How can I do that in Angular?

Duc Hoang
  • 335
  • 2
  • 8
  • 1
    Possible duplicate of [How to repeat a piece of HTML multiple times without ngFor and without another @Component](https://stackoverflow.com/questions/37676593/how-to-repeat-a-piece-of-html-multiple-times-without-ngfor-and-without-another) – charsi Feb 07 '18 at 10:42
  • Possible duplicate of [How to reuse template HTML block in Angular?](https://stackoverflow.com/questions/51086407/how-to-reuse-template-html-block-in-angular) – Andrey Kartashov Jul 13 '19 at 19:52

1 Answers1

1
<div *ngIf="Fordestop">
    <div class="divdesktop"></div>
    <template [ngTemplateOutlet]="my-reuse-div"></template>
</div>

<div *ngIf="ForMobile">
    <div class="divmobile"></div>
    <template [ngTemplateOutlet]="my-reuse-div"></template>
</div>

<ng-template #my-reuse-div>
<!--My reuse view-->
</ng-template>

You can also use ngFor in some cases. This will need an array with variables that change for each part.

https://angular.io/api/common/NgForOf

charsi
  • 2,917
  • 22
  • 40