8

I have a component "course". I use this component to a list. This list sometimes is horizontal and some times is vertical. Can I choose dynamicaly inside the component the template file?

@Component({
    selector: 'course',
    templateUrl: getTemplateFile()
})

Something like that would be great feature!

Michalis
  • 6,686
  • 13
  • 52
  • 78

2 Answers2

14

I think that this tutorial is very helpful

https://www.digitalocean.com/community/tutorials/angular-component-inheritance

You can simply extend your base component and overwrite the template. This allows you to have different components with the exact same functionality, but different templates.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Michalis
  • 6,686
  • 13
  • 52
  • 78
6

Sure, since angular 4, there is an *ngIf/else directive. You can switch the templates like this:

<div *ngIf="isHorizontal; else verticalTemplate">
  <span>horizontal</span>
</div>

<ng-template #verticalTemplate>
  <span>vertical</span>
</ng-template>

I guess, that you want to switch between horizontal and vertical layout depending on the screen width. So take a look at https://github.com/angular/flex-layout, which contains an ObservableMedia-Service.

Markus Kollers
  • 3,508
  • 1
  • 13
  • 17
  • 1
    Horizontal and vertical is just an example for me. The main purpose of my question is that I want my component have 2 different template files and choose which one i want to use. I don't want to load a template file with all the different templates. – Michalis May 26 '17 at 09:08
  • Are you using the angular-cli? – Markus Kollers May 26 '17 at 09:10
  • As far as i know, there is no way to dynamically load a template at this position, and i think it's not required. I think, the recommended way is to create two components, and switch between both in a parent component like in my answer. With the angular-cli, your templates will be bundled into the js-files, so they will be loaded anyways it will be used or not. The best way for lazy loading is with the router – Markus Kollers May 26 '17 at 09:17