POV
POV

Reputation: 12025

How to change template in Angular dynamically?

I need to substitute differ template if user comes from mobile device and another template if it is web.

How to change template in Angular dynamically?

I reviewed a few the same questions here, but they are about Angular JS

Upvotes: 1

Views: 5367

Answers (2)

asimhashmi
asimhashmi

Reputation: 4378

You can use ngTemplateOutlet to do this:

In your HTML:

<ng-container [ngTemplateOutlet]="getTemplate">

</ng-container>

<div>
  <button (click)="changeTemplate()"> Change Template </button>
</div>


<ng-template #webTemplate>
   <h3> Hey, I'm web template</h3>
</ng-template>
<ng-template #mobileTemplate>
  <h3> Hey, I'm mobile template</h3>
</ng-template>

In your component:

import { Component, ViewChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('mobileTemplate') mobileTemplate: TemplateRef<any>;
  @ViewChild('webTemplate') webTemplate: TemplateRef<any>;
  web: boolean;
  name = 'Dynamic Temmplates';
  constructor() {
    this.web = true;
  }
  get getTemplate() {
    if (this.web) {
      return this.webTemplate;
    }
    else {
      return this.mobileTemplate;
    }

  }

  changeTemplate() {
    this.web = !this.web;
  }
}

You can find the stackblitz demo here

More on NgTemplateOutlet here

Upvotes: 2

Sonaryr
Sonaryr

Reputation: 1122

you can use ng-template for this. Would look something like this:

<ng-container *ngIf="isWeb(); else mobileTemplate">
...
</ng-container>
<ng-template #mobileTemplate>
...
</ng-template>

For the isWeb() implementation I would use navigator.userAgent, see How do you detect between a Desktop and Mobile Chrome User Agent?

this way it will display the content in the ng-template when you are on mobile and the content in the ng-container otherwise.

Upvotes: 3

Related Questions