Rendering HTML from JSON with Angular 8

Viewed 5310

I have an Angular Storybook running with components in it.

I have a bit of JSON in the stories.ts of a component, one of the properties is a DIV's content, like so...

{
    "accordionLink": 'Accordion link 1',
    "accordionContent": "<p>Hello World!</p>",
}

The template HTML looks like this...

<li *ngFor="let accordionItem of accordionData; let i = index;">
    <a href="javascript:;" class="accordion-trigger" (click)="toggleAccordian($event, i)">
        {{ accordionItem.accordionLink }}
    </a>
    <div hide="!isActive">
        <div class="inner row">
            <div [innerHtml]="accordionItem.accordionContent"></div>
        </div>
    </div>
</li>

I tried getting the "accordionContent" HTML to render out in the actual DIV where the interpolation goes, but all I can get to show is the actual string (

Hello World!

), not the paragraph with all the styles etc applied...

Since the content of the DIV needs to be flexible (paragraphs, lists, etc), I would like to be able to put the HTML into the container, if this is at all possible.

Any help will be much appreciated. Thanks!

EDIT:

In the stories.ts file, I have my data set up like this...

const mockData = [
  {
    "accordionLink": 'Accordion link 1',
    "accordionContent": '<p>1 - Lorem ipsum dolor.</p>',
  },
  {
    "accordionLink": 'Accordion link 2',
    "accordionContent": '<p>2 - Lorem ipsum dolor.</p>',
  },
  {
    "accordionLink": 'Accordion link 3',
    "accordionContent": '<p>3 - Lorem ipsum dolor.</p>',
  },
];

In the same file, I set up my story to show in Storybook, like this...

template: `<ui-accordion [accordionData]="accordionData"></ui-accordion>`,
props: {
    accordionData: object('Content', mockData, 'General'),
}

In my component's .ts file, I have the content set up as an input...

@Input() accordionData: any;
3 Answers

Try using innerHTML instead of innerHtml

 <div [innerHTML]="accordionItem.accordionContent"></div>

You can achieve this with ngx-markdown

And bind your json HTML into [data]:

<li *ngFor="let accordionItem of accordionData; let i = index;">
    <a href="javascript:;" class="accordion-trigger" (click)="toggleAccordian($event, i)">
        {{ accordionItem.accordionLink }}
    </a>
    <div hide="!isActive">
        <div class="inner row">
            <markdown [data]="accordionItem.accordionContent"></markdown>   
        </div>
    </div>
</li>
Related