How to apply CSS classes to dynamically injected HTML in Angular 7

One of the challenges I'm currently facing is how to assign a CSS class based on a calculation in my component. Here's a snippet from my component class:

@Component({
  selector: 'app-render-json',
  template: `<div [innerHtml]="html | safeHtml"></div>`,
  styleUrls: ['./render-json.component.css'] , encapsulation: ViewEncapsulation.ShadowDom
})

export class RenderJsonComponent {
  @Input() myJson: any;
  html = ``;
  static levelDeep = 1
  
  ngOnInit() {
    this.renderJson(this.myJson)
  }
  
  renderJson(obj) {
    RenderJsonComponent.levelDeep = RenderJsonComponent.levelDeep + 1
for(var key in obj) {
      if(key != 'id') {
        this.html = this.html + `<div class="col-md-${RenderJsonComponent.levelDeep}  col-md-offset-${RenderJsonComponent.levelDeep}">${obj[key]}</div>`
        // Although the intended code does not work, I aim to achieve something similar
      }
}
}
}

In essence, I am trying to display JSON data in a responsive grid layout using Bootstrap offset classes, but encountering difficulties in getting it to work properly. Any suggestions or guidance would be greatly appreciated.

Answer №1

@Component({
  selector: 'app-render-json',
  template: `<div [innerHtml]="safeHtml"></div><div *ngFor="jsonElements as element" class="element.class">element.obj</div>`,
  styleUrls: ['./render-json.component.css'] , encapsulation: ViewEncapsulation.ShadowDom
})

export class RenderJsonComponent {
  @Input() myJson: any;
  myLevelDeep = 1;
  jsonElements = [];

  ngOnInit() {
    this.renderData(this.myJson)
  }

  renderData(obj) {
    this.myLevelDeep = RenderJsonComponent.levelDeep + 1
        for(var key in obj) {
      if(key != 'id') {
        jsonElements.push({class:"col-md-" + this.myLevelDeep + " col-md-offset-" + this.myLevelDeep, obj: obj[key]});
      }
        }
    }
}

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

Is there a way for me to confirm the presence of a particular object within an array and return a true value

I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role. Here is my current approach: <form [formGroup]="rolesForm"> <label formArrayName="roles" *ngFor=" ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

Is there a way for me to extract information from a static HTML page, like the meta tag, in a simple manner

In my Angular 2 application, I am using Flask (Python framework) to serve up the static HTML content when accessed through the index. My goal is to show the version of the application on the AboutComponent. Currently, I have Flask injecting the version int ...

Animating with Angular 2

As I delve into this informative resource, my goal is to incorporate some animations into my applications, but I find myself grappling with understanding how the animations are triggered. HTML Component <div class="navbar navbar-default navbar-fixed-t ...

Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty. Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding ...

Guide on transforming an Angular 6 project into a Progressive Web Application (PWA)

Currently, my Angular 6 project is up and running smoothly. However, I am looking to integrate PWA into my existing application. When I execute the following command: ng add @angular/pwa The output displays: + @angular/<a href="/cdn-cgi/l/email-protec ...

What is the best way to integrate Angular npm into a TypeScript React project?

At my workplace, I've been tasked with working on a project using React and TypeScript. They also want me to integrate an Angular library from npm. I'm wondering if it's feasible to do this integration or if I should create my own library in ...

Update overall font size to be 62% for a consistent look across the website

Recently, I developed a browser extension that adds an overlay button to the LinkedIn website. Everything was running smoothly until I discovered that LinkedIn uses a global font-size: 62,5% that completely messes up my design.. https://i.stack.imgur.com ...

Is it possible to resize background images on Safari?

Encountering an issue with Safari where the background isn't scaling properly. It functions perfectly in Firefox, Chrome, and other browsers, but Safari is presenting a problem. Here's a link to the site: This issue occurs when the resolution is ...

Issue with Bootstrap columns being misaligned on mobile devices

On my website, I've implemented a Bootstrap Grid design with three columns under the container-fluid BS attribute, along with .row .no-gutters. While the boxes are perfectly aligned in the desktop view, they stack vertically on mobile and tablet devi ...

Steps to animate a div expanding to fit its content dimensions

I'm looking for a way to animate the opening of a div so that it adjusts to the size of its content. The content is fetched from a separate search using .load, which means it could be just a single line (no result) or multiple results that vary in hei ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

What could be causing the issue with my Date and Time input not functioning correctly?

I developed a React frontend application styled with Material UI design. The issue I am facing is that after adding the Date and Time component styling to the form, it is unable to process the "name" value for posting. Specifically, the error message "Ty ...

Preventing Paste Function in Electron Windows

Currently, I am utilizing Electron and attempting to prevent users from pasting into editable content. While paste and match style remains enabled, the functionality is flawless on Mac devices. However, there seems to be an issue on Windows where regular ...

Silencing the warning message from ngrx/router-store about the non-existent feature name 'router'

After adding "@ngrx/router-store" to my project, I noticed that it fills the app console in development mode and unit test results with a repeated message: The warning states that the "router" feature name does not exist in the state. To fix this, make ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

I followed the step to download Angular using NPM Install

When attempting to work on a repository that uses Angular without having it installed on my machine, I ran npm i. However, Angular was not automatically installed. So, I had to separately install the Angular CLI before running ng serve --open ...

There was an issue encountered when creating the class: The parameters provided do not correspond to any valid call target signature

I am facing an issue with my code. Here is the scenario: export class MyClass { public name:string; public addr:string; constructor() {} } I have imported MyClass and trying to use it like this: import { MyClass } from './MyClass' ...

Encountering a runtime issue when implementing Ng2-charts within an Angular/Node.js project

I encountered an error while running my Angular4 - Node.js application. The error message states: Can't bind to 'data' since it isn't a known property of 'canvas'. ("iv> ][data]="doughnutChartData" [labels]="doughnutChart ...

A guide to changing the height of a column in Bootstrap

I've utilized Bootstrap to create features in the HTML, and I'm attempting to make each box's height consistent. Check out a screenshot of the boxes here #hr-1 { width: 100px; margin-left: 20%; } #features { background-color: #f0 ...