"Enhancing User Experience with Angular 2: Customizing Component Selection and Sty

I am currently working on an Angular application that fetches a configuration file in .json format. My goal is to dynamically choose components and apply inline styles to them.

Below is an example of the structure of the configuration data obtained from an HTTP request:

For instance;

var config = [
  {
    name: "header-component",
    styles: "margin:0;padding:0;background:black"
  }
]
<div *ngFor="let conf of config">
  <{{conf.name}} style="{{conf.styles}}"></{{conf.name}}>
</div>

Do you have any suggestions on how I can make this work, or do you recommend an alternative approach?

Answer №1

angular doesn't bind var variables to the DOM. Utilize it in this manner

config :{ name: string, styles: string }[]= [
  {
    name: "header-component",
    styles: "margin:0;padding:0;background:black"
  }
]

updated

You can create a @pipe and bind the HTML. Modify the JSON like this.

config :{ name: string, styles: string, html : string }[]= [
      {
        name: "header-component",
        styles: "margin:0;padding:0;background:black",
        html : "<{{conf.name}} ngStyle='[conf.styles]'></{{conf.name}}>"
      }
]

Add this pipe to your code

@Pipe({name: 'safeHtml'})
export class Safe {
  constructor(private sanitizer:Sanitizer){}

  transform(style) {
    return this.sanitizer.bypassSecurityTrustStyle(style);
    // return this.sanitizer.bypassSecurityTrustHtml(style);
    // return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
  }
}

Call the pipe in the HTML

<div *ngFor="let conf of config">
  <div [innerHTML]="conf.html | safeHtml"></div>
</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

Encountering Error TS2411 when upgrading from Typescript version 1.0.0 to 1.1.0-1

After updating my TypeScript using npm install typescript -g, I have been encountering a recurring error during compilation. Although the compilation is successful, it's becoming tedious. cmd.exe /D /C C:/Users/Vado/AppData/Roaming/npm/tsc.cmd --sour ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

Solving commitments through a series of actions

Can someone please explain why when resolving promises in a loop, accessing the loop variable is necessary for it to work correctly? Here's an example where logging occurs 5 times: for (let i = 0; i < 5; i++) { this.getData() .then(() ...

Access the most up-to-date information through the API URL

Objective: Whenever the 'Test' Button is clicked, new data must be fetched from the backend using the API link and displayed on the modal form. Issue: If text in the input box is changed or deleted, then the modal is closed and the 'Tes ...

Angular2 RC5 causing switchMap to fail in ngrx/effects

Recently in my Angular2 application, I've been utilizing ngrx/effects. However, with the release of RC5, I started encountering errors in my code. Here's a snippet: import { Injectable } from '@angular/core'; import { Effect, Actions } ...

Invoking Angular component method using vanilla JavaScript

For my web application, I am utilizing Angular and require Bluetooth functionality on a specific page. I am implementing loginov-rocks/bluetooth-terminal (https://github.com/loginov-rocks/bluetooth-terminal) for establishing the Bluetooth connection, which ...

When transferring the code to the src folder, tRPC encounters issues and stops functioning

Currently, I am working on developing a basic Twitter clone using Next and TRPC. While tRPC is up and running smoothly, I am looking to streamline my code by consolidating it all within the src directory. However, upon moving everything, I encountered an i ...

Waiting for completion of two observables in RxJS/Angular 11 while also managing errors

Currently, I am facing the challenge of waiting for two requests to complete (observables) and performing certain actions. Here is what I need: Wait for both requests (observables) to finish If one of them fails - show one error message If both of them f ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

Guide on creating frozen columns in an Angular 2 table with the ability to scroll through multiple columns

Within my table, there are 3 columns that must always remain on the left side. Additionally, there is a column containing a grid where each element represents an hour of the day, requiring it to be scrollable. I have attempted various proposed solutions, ...

concerning the integration of CSRF token in the GuestPayment feature

Greetings and thank you for taking the time to help me out. I am currently working on a project in AngularJS 2.0 where users need to be able to pay their pending bills through a GuestPayment portal. This portal does not require any login credentials and ...

Error encountered with TypeScript compiler when using a React Stateless Function component

I am attempting to create a React Stateless Function component using TypeScript. Take a look at the code snippet below: import * as React from 'react'; import {observer} from 'mobx-react'; export interface LinkProps { view: any; ...

What steps can be taken to choose an Angular npm package for datetimepicker in a TypeScript file?

I am facing an issue where document.getElementById and document.querySelector are not returning any results ... I need to access this specific HTML element in order to set a new attribute at a certain event. <datetime id="datePicker" [datepicker]="da ...

What steps can I take to fix error TS7015 in my TypeScript, Next.js, and React application when I encounter an index expression that is not a number data type?

I encountered an error stating "Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)" The file I imported is import { useAmazon } from "@context/amazon"; I used it as follows con ...

What is the best way to insert an item into a tree structure when determining the appropriate level for insertion is necessary beforehand?

Currently, I am dealing with a tree-like object structure: interface Node { id: number; name: string; children?: Node[]; } NODE_DATA: Node[] = [ { id: 1, name: 'A' }, { id: 2, name: 'B', children: [ ...

Inference of generic types within a TypeScript generic

In my coding journey, I came across a situation where I was dealing with generic classes. Specifically, I had a Generic class Generic<T> and another one called GenericWrap that used Generic as its maximum type parameter (denoted as U extends Generic& ...