"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

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

Implementation of setProperties method on LineLayer in MapBox encounters resolution issues

I am currently utilizing the Android Mapbox SDK to integrate a VectorSource into a MapboxMap and then I am trying to incorporate a LineLayer onto the map as well. My version is 5.1.3 This code will be written in TypeScript due to its compatibility with t ...

Implement the agmCircle method from angular-google-maps in a typescript file

Is there a way to retrieve the bounds of a circle once it has been changed? I noticed on that there is a "getBounds" method available. How can I access this method from my typescript file in order to log this data? This is how my html circle component cur ...

Guide on generating a request through iteration using Javascript

I'm currently working on a request that involves multiple methods, and I want to streamline the code by using an enum to iterate through and construct the request. However, my attempt at doing this has resulted in unexpected outcomes. The original co ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

One-stop shop for organizing import paths

Currently seeking a solution to streamline the management of import paths in Angular 2.0. Ideally, I would prefer to set up the configuration once and then simply reference it as needed, similar to using a variable. For instance: import { ProductService } ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Sending additional parameters through an HTTP request in Angular

I've created a service method in Angular 8 with an optional parameter. However, I'm encountering a compile time error that says no overload matches this call. The error seems to be at the return statement. Can anyone help me figure out what' ...

Methods for showing Internet Explorer not supported in Angular without needing to import polyfills

Due to the deprecation of IE in Angular 12, I need to inform users to switch to a supported browser by displaying a static warning on my page. To achieve this, I have implemented a simple snippet in the index.html file that appends a CSS class to the body ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Utilizing Angular2 with Firebase for efficient denormalized data queries

I am currently working on crafting a query for a denormalized database. Drawing inspiration from the example showcased in Firebase's blog post, my objective is to: Retrieve the array of forms associated with the current user and return references to ...

Issue with React TSX component in NextJs 14.0.4: Local MP3 files cannot be played, only external online MP3 files work

I have created a component that wraps around HTML audio and source tags. It functions perfectly when playing mp3 files from an external source, like this sound clip . However, it returns a GET 404 error when trying to access local mp3 files. Can anyone exp ...

How to update Angular Material table dynamically after CRUD operation without needing to reload the page

Hello, I am currently using Angular (v.9) along with ASP .NET Core Web API and EF Core (v 3.1) to perform CRUD operations. I have a region component form which is used as a dialog, you can view it https://i.stack.imgur.com/6w7hO.png The HTML code for the ...

Retrieve the output of a function in TypeScript

I'm encountering a challenge with returning a string instead of a function in an object value. Currently, an arrow function is returning an array of objects, and one of them needs to conditionally change a value based on the input value. Here is the ...

Angular Iterate Array Forms

Is there a way to iterate my rows based on user input? For example, if the user enters 2 values, I need to display 2 rows. How can I achieve this using FormArray? setCount(count:any){ console.log(count); this.count = count; this.countArray = Ar ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Error in Node.js with MongoDB: Array of OptionalId<Document> Typescript typings

I have successfully established a connection and written to my MongoDB collection, but I am encountering a type error that is causing some confusion. Below is the code snippet along with the error message: interface Movie { id: number; title: string; ...

Modify the MUI time picker to display as a digital clock inside a DateTimePicker widget

I need to update my MUI DateTimePicker component to use the DigitalClock time picker instead of the Analog Clock picker. The current component has two steps, first picking the date from a calendar and then selecting the time. This change is only necessary ...