简体   繁体   English

从Angular中的JSON生成HTML

[英]Generating HTML from JSON in Angular

Im trying to generate HTML code to Angular component template from JSON and im looking for best practice. 我试图从JSON生成HTML代码到Angular组件模板,我正在寻找最佳实践。

Actually Im fetching JSON and use *NgFor and *NgIf to achieve that 实际上我正在获取JSON并使用* NgFor和* NgIf来实现这一点

const blocks = [
    {
      id: '1',
      type: 'header',
      fields: [{
        content : 'H1 Header'
      }]
    },
    {
      id: '2',
      type: 'image',
      fields: [{
        src : 'https://i.pinimg.com/originals/5e/f6/83/5ef68313994aaf68e87d190de943f104.jpg',
        title: 'My Image'
      }]
    },
]
<mat-accordion multi="true" *ngIf="blocks.length > 0">
  <mat-expansion-panel *ngFor="let block of blocks">
    <mat-expansion-panel-header>
      {{ block.type }}
    </mat-expansion-panel-header>
    <ul>
      <div *ngFor="let field of block.fields">
        <div *ngIf="block.type == 'header'">
          <h1>{{ field.content }}</h1>
        </div>
        <div *ngIf="block.type == 'image'">
          <img style="width:100%;" src={{field.src}} />
        </div>
        <div *ngIf="block.type == 'paragraph'">
          <p>{{field.content}}</p>
          </div>
      </div>
    </ul>
  </mat-expansion-panel>
</mat-accordion>

Is there better way to do that? 有没有更好的方法呢?

相反,如果使用几个ngif,我会使用ngswitch

this is not a good practice, in angular you have a template and you should bind properties and events to make your app dynamic. 这不是一个好习惯,角度你有一个模板,你应该绑定属性和事件,使你的应用程序动态。 Keep in mind that angular sanitizes your input so for example you cannot render scripts and style in the way you are tryng to do so you won't be able to rendere an entire page. 请记住,角度会对您的输入进行清理,例如,您无法以尝试的方式呈现脚本和样式,因此您将无法呈现整个页面。 If you want to change a title dynamically you can do something like this: 如果要动态更改标题,可以执行以下操作:

// in your component
title: string;

// in template
<h1>{{title}}</h1>

same for image 同样的图像

// in component
src: string;

//in template
<img [src]="src">

Angular is made to build apps, but apps have a structured page, if not what kind of app would you build? Angular用于构建应用程序,但应用程序有一个结构化页面,如果不是你会构建什么样的应用程序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM