Tips for dynamically displaying Angular Material tags within an Angular component using JSON data

I received a JSON response structured 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>',
 }

However, when I tried to render the star icon, it did not display as expected. Here is the code snippet from my component:

<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 displayed output can be seen in the following screenshot: https://i.sstatic.net/YbmiJ.png

I'm wondering if this is the correct way to display the content, or should I possibly generate the tags inside the Angular component?

Expected Result:

https://i.sstatic.net/cGAZA.png

Answer №1

The issue at hand

The root of your problem lies in attempting to dynamically load a component during runtime, which is not feasible using solely HTML.

To understand more about dynamic component loading, refer to this informative article. Since `mat-icon` is not recognized as an HTML element, the browser cannot interpret it correctly, leading to unexpected results.

Furthermore, incorporating HTML content from an API into your application poses significant security risks due to the potential injection of malicious code and HTML elements.

A viable solution

To address this issue, transmit the star ratings as numerical values from your backend server. Implement an `ngFor` directive with `mat-icon` elements nested within to display the corresponding number of stars accurately.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

What methods does TypeScript use to verify primitive types during runtime?

Is it true that Typescript removes any type or interface at compile time? If so, how is it possible to determine an object's primitive type using the typeof keyword? Are custom interfaces handled differently than primitive types? const a = "strin ...

Why is my Vue view not being found by Typescript (or possibly Webpack)?

npx webpack TS2307: Cannot locate module './App.vue' or its corresponding type declarations. I am currently utilizing webpack, vue, and typescript. My webpack configuration is pretty basic. It uses a typescript file as the entry point and gener ...

Issues with Angular unit tests failing due to an unexpected phantomJS error

Executing ng test triggers the execution of my 3 unit tests which have been hardcoded to pass successfully, as shown below: describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ ...

What is the best way to time a Google Cloud Function to execute at the exact second?

In my attempt to schedule a cloud function using the Pub/Sub trigger method along with crontabs, I realized that it only provides granularity to the nearest minute. However, for my specific application - which involves working with trades at precise time ...

The TypeScript error message states, "The property 'breadcrumb' is not found within the type 'Data'."

My Breadcrumb Component is functioning properly when compiled to JavaScript and displaying the desired output. However, my IDE is showing an error message that I am struggling to fix. The error states: [ts] Property 'breadcrumb' does not exist o ...

How to fill an HTML template using ngFor without using a JSON array

Is there a way to fill the HTML with basic JSON like below: { "id": 34, "name": "Tip 33", "description": "Tip description 33", "created_at": "2018-01-26 18:59:19", "updated_at": "2018-01-26 18:59:19" } The code i tried using was: < ...

Validation of input type number restricted to only numeric values

Is there a way to validate an input field with type="number" using only Reactive Forms in Angular, ensuring that the value is either numeric or null without utilizing directives? Only numbers [0-9] and . are permitted, no other characters. My Approach: ...

What is causing so many issues when this component is integrated? (the scope of issues will be detailed later on)

I have the following 3 components: news-feed.component user-activity-item.component user-activity-list.component Both user-activity components are located within a subdirectory of the news-feed component. Additionally, the user-activity-item is just a ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

The Angular2 application encountered a 404 file not found error while trying to read a Const from a ts

Recently I started working with angular2 and encountered a problem when trying to access constant values from an external .ts file using the following code: import {apis} from '../constants/apis'; The content of the constants/apis.ts file is as ...

Tips for modifying the UserRepresentation in keycloak REST API response

Whenever we send a GET request to the following URL: https://my-keycloak/admin/realms/test-realm/users We receive a comprehensive list of users who are associated with the test-realm. According to the Keycloak REST API documentation, this kind of respons ...

What is the process for accessing NGXS selectors during unit testing?

When subscribing to the selector teamMemberService$, we expect a list to be returned, followed by some checks. I need to write tests for this code snippet, but I am unsure how to approach testing this type of subscription. if (this.doctor != undefined) ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...

What steps are required to customize a pre-existing DevExtreme JQuery DataGrid that was initially built in a cshtml file using Typescript?

I'm currently developing a web application using DevExtreme JQuery. Within the frontend, I have set up a DataGrid in a cshtml file. With DevExtreme functionality, it's possible to include an Add Button to the DataGrid that triggers a popup for in ...

Troubleshooting the issue of Child redirect in Angular4 Routing not functioning

My Angular4 routing setup looks like this: {path: 'siteroot', component: SiteMessengerComponent}, { path: '', component: FrameDefaultComponent, children: [ { path: 'user/:userId', component: SiteUs ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

Dynamic module declaration - Typescript 3.5

In TypeScript, I am able to declare a module like this: declare module '*.svg' { const content: string export default content } After declaring the module, I can import it using import svg from './src/file.svg' without encount ...

TypeScript and Node.js: The type of 'this' is implicitly set to 'any'

Help Needed with TypeScript issue: An issue is arising in my TypeScript code related to a mongoose schema's post function. It is used to generate a profile for a user upon signing up, using the User model. Even though the code functions properly, th ...

The form input is not being populated as expected after being retrieved from the service

Currently, I am constructing a form using Angular 5 within a material popup that includes both a select box and text fields. The issue arises when the select box value is fetched from a service, causing a delay in populating the select box for the user. ...