【问题标题】:How to render angular material tags from JSON response inside angular component?如何从角度组件内的 JSON 响应呈现角度材质标签?
【发布时间】:2019-11-17 05:18:56
【问题描述】:

我有一个像这样的 json 响应

 {
      _id: '5dd0d0dc4db1cf9c77781aaa',
      picture: 'http://placehold.it/32x32',
      name: 'Graciela Mcmahon',
      guid: '98c0fcc2-1dfc-4974-bdae-d8263d783e0a',
      star:
        '<mat-icon>star</mat-icon><mat-icon>star</mat-icon><mat-icon>star_half</mat-icon><mat-icon>star_border</mat-icon><mat-icon>star_border</mat-icon>',
 }

当我开始渲染时,它没有按预期渲染 我的组件代码

<owl-carousel-o [options]="listingSliderOptions" class="row">
    <ng-container *ngFor="let listing of listingJson">
      <ng-template carouselSlide [id]="listing._id">
        <a [routerLink]="['/']" class="listing-grid-item">
          <figure>
            <img src="{{listing.picture}}" alt="" />
            <div class="info">
              <div class="cat_star" [innerHTML]="listing.star">

              </div>
              <h3>{{listing.name}}</h3>
            </div>
          </figure>
        </a>
      </ng-template>
    </ng-container>
  </owl-carousel-o>

以上代码显示为

这是正确的显示方式还是我必须在 Angular 组件中生成标签?

预期结果

【问题讨论】:

  • 你说它没有按预期呈现,但你没有表明你做什么期望......
  • 我编辑了我的问题i.stack.imgur.com/cGAZA.png@RoddyoftheFrozenPeas
  • 不,你不能那样做。不要将 Angular HTML 标记放在 JSON 中。放数据。在这种情况下,要显示的星数。并在您的组件模板中,放置显示该星数所需的代码。

标签: angular typescript angular-material owl-carousel


【解决方案1】:

问题

您的问题源于您试图在运行时动态加载组件。不能指望纯 html 会发生这种情况。

阅读this article here 以获取动态组件加载。 mat-icon 不是 html 元素,因此浏览器不知道如何处理它,因此您会得到这个奇怪的结果。

在您的应用程序中加载来自 api 的 html 也是一种非常糟糕的安全做法,因为可能会注入恶意代码和 html。

解决方案

从您的后端以数字形式发送星星。创建一个 ngFor 并在其中定义 mat-icon 并迭代任意多次以创建星星。

<div class="cat_star">
      <ng-container *ngFor="let star of listing.star">
          <mat-icon>{{ star }}</mat-icon>
      </ng-container>
 </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 2019-06-14
    • 2016-02-23
    • 2019-04-05
    • 2020-03-10
    相关资源
    最近更新 更多