Michalis
Michalis

Reputation: 6936

Angular - Component different templates

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!

Upvotes: 8

Views: 23374

Answers (2)

Michalis
Michalis

Reputation: 6936

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.

Upvotes: 14

Markus Kollers
Markus Kollers

Reputation: 3728

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.

Upvotes: 6

Related Questions