Home:ALL Converter>Generate complex html from JSON at Angular2

Generate complex html from JSON at Angular2

Ask Time:2021-09-22T19:10:39         Author:tsinevik

Json Formatter

We writing app in Angular. In our app we need to write articles, so we decided to use Editor.js for that. Right now we having problem of how to correctly parse JSON-article and generate HTML out of it. For articles we are having JSON object such as this.

        {
            "id" : "1",
            "type" : "header",
            "data" : {
                "text" : "Main title",
                "level" : 1
            }
        },
        {
            "id" : "2",
            "type" : "paragraph",
            "data" : {
                "text" : "Some text <mark>something</mark>"
            }
        },
        {
            "id" : "3",
            "type" : "list",
            "data" : {
                "style" : "unordered",
                "items" : [
                    "list-item 1",
                    "list-item 2",
                    "list-item 3"
                ]
            }
        },
        {
            "id" : "4",
            "type" : "image",
            "data" : {
                "file" : {
                    "url" : "www.com/test.png"
                },
                "caption" : "",
                "withBorder" : false,
                "stretched" : false,
                "withBackground" : false
            }
        }

For simple JSON I would without a doubt generate HTML inside Angular template, but with our needs we may have even more complex blocks with many style options, so I think like it would be too much logic to process at template and it may slow our app. For example, for image we have to use conditionally different classes or styles based on properties such as caption, withBackground, stretched, withBorder. And we may have multiple images in article and other blocks that have many style options.

Another way is to parse JSON at .ts file and map all blocks to html-string with certain classes and styles. But then if we would have something like image-gallery or slider or some other complex block we would have to generate very big string, which as I think would be better to replace with separate component, but then as I understand we won't be able to use component selector as string in a template. Also I think in case of generating html inside .ts file we may have a problem with style encapsulation.

So my question is what is a best way to generate HTML from such a complex JSONs? Would it really slow our app down if we put complex logic inside template? Maybe there's a third or fourth way to do that?

Author:tsinevik,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69283031/generate-complex-html-from-json-at-angular2
yy