5

I am working in angular 8, i have a component for which i have around 6 or more templates. user will select from interface or some logic that which one to use, let say,

if(a==2) use template 'ddd.html'
else user template 'sss.html'

I don't want to use it here

@Component({
selector: 'app-maindisplay',
  templateUrl: './maindisplay.component.html',
  styleUrls: ['./maindisplay.component.css']
})

I want it in any function either it be constructor or any other function. It will be okay if it uses any child component or directive kind of logic to solve, my only need is to choose template on that logic. I will pass same data to all templates usually, only their design will be changed.

Bill P
  • 3,622
  • 10
  • 20
  • 32
Muhammad Aadil Banaras
  • 1,134
  • 1
  • 11
  • 21

1 Answers1

2

I had the same problem and I was searching for the same solution you're asking for, but I didn't found any. I solved the problem with inheritance. You have to create a component without any template which will be the parent class. This component will contain all the logic you need. I insert only an Input just to show how it works:

base.component.ts

@Component({
  selector: 'base',
  template: ''
})
export class BaseComponent{
  @Input()
  text: string;
}

Then you have to create different templates as different components which extends BaseComponent:

template1.component.ts

@Component({
  selector: 'template1',
  template: '<button>{{text}}</button>'
})
export class Template1Component extends BaseComponent{} 

template2.component.ts

@Component({
  selector: 'template2',
  template: '<input [value]="text">'
})
export class Template2Component extends BaseComponent{} 

And now you can simply use them like this:

app.component.html

<button (click)="template = (template == 1) ? 2 : 1">Change template</button>
<br><br>
<ng-container [ngSwitch]="template">
  <template1 text="Template1 input text" *ngSwitchCase="1"></template1>
  <template2 text="Template2" *ngSwitchCase="2"></template2>
</ng-container>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  template = 1;
}

Take a look to the working example here

Hope this could help.

Federico Galfione
  • 1,069
  • 7
  • 19
  • 1
    yeah it seems great, but still you are adding template as fixed in child components, like you added 2 child components and chossing which one to use by logic, my issue is i am ok to use a child component, but templates should be selected by logic, like parent component sends data to child like use template abc.html or dd.html then that child component should add that as template. not like add component for new template, i need one component to select anyone of the given templates. – Muhammad Aadil Banaras Sep 18 '19 at 06:42