Zoidy
Zoidy

Reputation: 384

Angular 2 dynamic templates

I am developing something like a CMS. I have articles which have templates. Articles are added on backend and I need to display them using templates (when I am rendering the article, I know which template to use). Since there will 10s of templates, I am trying to figure out what is the best way to store the templates and how to load the correct template according to loaded article. What I am considering:

I am looking for an architectural and technological solution. I would love to go with option 1, but don't know how to build a template for article component. I would love to have just one component, which gets the article and just loads (builds) the needed template.

Angular2 RC5

EDIT:

template A: set A of css rules (blue text, caps for headlines), headline, paragraph, image, paragraph and a link somewhere else (inside the paragraph) template B: set B of css rules (red text, regular headlines), headline, carousel for images, one paragraph

{
"templateId": 1,
"title": "Article title",
"elements": [{
    "text": "paragraph text"
}, {
    "image": "http: //someurl.com"
}, {
    "text": "another paragraph text"
}]

}

Upvotes: 3

Views: 525

Answers (1)

cDecker32
cDecker32

Reputation: 811

I think your best bet is to have a component for each style, with a parent component that uses an ngSwitch to swap between the articles. So...

<article-component>
  <div ngSwitch="article.type">
    <template-a *ngSwitchCase="a" [article]="article">
    </template-a>
    <template-b *ngSwitchCase="b" [article]="article">
    </template-b>
    <template-c *ngSwitchCase="c" [article]="article">
    </template-c>
  </div>
</article-component>

Beyond that I'm not sure what else you can do without knowing what the "article" data model looks like.

EDIT: Ok after seeing your proposed data model, inside your templates you could do a ngSwitch inside an ngFor that iterates over your "elements" array. I know this is kind of janky, but it's likely your best bet. And then obv shared "paragraph", "image", and "carousel" components to be used between the different article templates.

Upvotes: 1

Related Questions