Search code examples
angulartypescriptangular-materialowl-carousel

How to render angular material tags from JSON response inside angular component?


I have a json response of like this

 {
      _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>',
 }

When i render start it did not render as expected my component code

<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>

The above code display as enter image description here

Is this right way to display or i have to generate tag inside Angular component ?

Expected Result

enter image description here


Solution

  • The problem

    Your problem stems from the fact that you are trying to dynamically load a component in runtime. This can't be expected to happen with pure html.

    Read this article here for dynamic component loading. mat-icon is not an html element so the browser does not know what to do with it, thus you have this weird outcome.

    It is also a very bad security practice to load html in your application, that comes from an api as malicious code and html could be injected.

    Solution

    Send the stars as a number from your backend. Create an ngFor with mat-icon defined in it and iterate as many times as you want to create the stars.

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