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:

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:

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

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Include additional information beyond just the user's name, profile picture, and identification number in the NextAuth session

In my Next.js project, I have successfully integrated next-auth and now have access to a JWT token and session object: export const { signIn, signOut, auth } = NextAuth({ ...authConfig, providers: [ CredentialsProvider({ async authorize(crede ...

Can Angular Material allow for unique CSS styling on each component?

As stated in the Angular Material Documentation, it is necessary to include the entire theme in order for the framework to function properly. This entails styles for all components. However, I am creating a component library and only pulling specific comp ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

NG8001: The element 'app-servers' is unrecognized

Oh no! Issue I've tried everything but can't seem to fix it I'm using the same selector but the problem persists It's supposed to show a label, input box, and button. I've tried all suggested solutions but none have worked for ...

Angular - personalized modal HTML

I am facing a challenge where I need to trigger a popup when a button is clicked. There can be multiple buttons, each with its own overlay popup, and these popups should close when clicking outside of them. Currently, I am using TemplateRef (#toggleButton ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

What causes the variation in Http Post Response between the Console and Network response tab?

Currently, I am tackling an issue in angular2 related to HTTP post response. The problem arises when my endpoint is expected to return a boolean value. Interestingly, the response appears correctly in Chrome's Network response tab; however, upon loggi ...

Defining Multiple Types in Typescript

I have created an interface in a TypeScript definition file named d.ts: declare module myModule { interface IQedModel { field: string | string[]; operator: string; } } In an Angular controller, I have utilized this interface like ...

The service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so: rule.service.ts @Injectable() export class RuleService { constructor( private _resourceService: ResourceService ){} s ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

What connections exist between systemjs.config.js and .import() in Angular2/SystemJS?

My journey to learn Angular2 has led me to various Stack Exchange posts and internet articles discussing the function of systemjs.config.js. However, I've noticed that most explanations tend to use the term "app" excessively. For example, when index. ...

Using Angular 4 with Semantic-UI for Dropdown menus

Currently, I am in the process of implementing an Angular directive to handle Semantic UI dropdown. My setup includes Angular (4.3.3), jQuery (3.2.1), and Semantic UI (2.2.13) installed via npm. To make these libraries work together, I made modifications ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

There is no corresponding version available for [email protected] in Angular 6

After cloning a project from git, I attempted to run npm install. However, an error message popped up, as shown in the following link: https://i.stack.imgur.com/pqYbK.png Can someone please explain why this is happening and how I can resolve it? Any help ...

The data type 'Observable<{}[]>' cannot be matched with the type 'AngularFireList<any>'

I have been learning how to use AngularFire2 by following this tutorial. Encountered the error: 'Type 'Observable<{}[]>' is not assignable to type 'AngularFireList'. Property 'query' is missing in type 'Observa ...

Bypassing disputes in a TypeScript function

I attempted to implement the solution provided by Pacerier in response to the question about skipping arguments in a JavaScript function. However, it doesn't seem to be working for me. The function I am dealing with has numerous arguments. this.servi ...

Avoiding Maximum Call Stack Size Exceeded in Observables: Tips and Tricks

After filtering, I have a list stored in the variable filteredEvents$: public filteredEvents$ = new BehaviorSubject([]); I also have a method that toggles the checked_export property and updates the list: public checkAll(): void { this.filteredEve ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...

Obtaining the value of SCOPE_IDENTITY to be used in an Angular application

Having trouble getting the ID of the newly inserted table row to use in my Angular application. Any suggestions on how to pass it while posting? Can't quite figure it out. public string Post(Profile profile) { try { string ...