Insert dynamic values into div attributes

I am looking for a way to dynamically add div attributes in Angular 7.

Here is what I attempted:

<div *ngFor="let e of etats._embedded.etats" 
style="background: {{e.codeCouleur}} !important;"  
data-code="{{e.id}}" data-bg={{e.codeCouleur}}>{{e.nom}"</div>

However, I encountered the following error:

Error: Template parse errors: Can't bind to 'code' since it isn't a known property of 'div'. (" *ngFor="let e of etats._embedded.etats" style="background: {{e.codeCouleur}} !important;" [ERROR ->]data-code="{{e.id}}" data-bg={{e.codeCouleur}}>{{e.nom}"

Answer №1

To efficiently loop through dynamically, you can utilize a code structure like the following:

<div *ngFor="let item of itemsList._embedded.items" 
     [style.backgroundColor]="item.colorCode"
     [data-id]="item.identifier" 
     [data-bg]=item.colorCode
>{{item.name}}"</div>

Answer №2

Here are a few possibilities:

  • <span attribute="{{value}}"/></span>
  • <span [attr.attributeName]="value"/></span>
  • <span [attr.attributeName]="getValueFunction()"/></span>

Answer №3

The concept you are aiming for is known as Attribute Binding. Quoting from the official documentation:

When there is no element property available to bind, attribute binding must be used.

Based on this explanation, a slight modification needs to be made in your code. For handling the style, options such as ngStyle or [style.background] can be utilized; however, the usage of !important may not yield the expected results:

<div *ngFor="let e of etats._embedded.etats" 
  [ngStyle]="{'background': e.codeCouleur}"  
  [attr.data-code]="e.id" [attr.data-bg]="e.codeCouleur">{{e.nom}}</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

Different return types of a function in Typescript when the parameter is either undefined or its type is explicitly asserted vary

Addressing Complexity This code may seem simple, but the use case it serves is quite complex: type CustomFunction = <B extends ['A']>( param?: B ) => B extends undefined ? 'TYPE_1' : 'TYPE_2' // Usage examples: co ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

Error encountered during password reset in Auth0

I am currently working with Angular 2 and using lock version 10.8 in an attempt to implement a feature that allows users to change their password. I've been experimenting with the following method, which involves calling the Management API. In this me ...

Unusual title attributed to saving the date in Firebase

Could anyone explain why my JSON appears like this https://i.stack.imgur.com/xzG6q.png Why does it have a strange name that starts with -M-yv... instead? I am saving my data using the http.post method, passing the URL to my database and an object to save ...

Is there a way for me to retrieve the text generated by OpenAI in the completion response?

let gptResponse = await openai .createCompletion({ model: "davinci", prompt, max_tokens: 60, temperature: 0.9, presence_penalty: 0, frequency_penalty: 0.5, best_of: 1, n: 1, stre ...

Creating a DIV element in Angular 5 component rather than using a new tag

Is there a way to instruct Angular to generate a DIV instead of another tag when inserting a component into a router-outlet? Currently, the component code looks like this: import { Component, OnInit, ViewEncapsulation } from '@angular/core'; @C ...

Angular: Exploring Directives - The Impact of Passing "null" versus an Empty String to the @Input Setter

I've observed an interesting behavior with the @Input setter in a Directive. It seems that when an empty string ("") is passed in the template, the setter method is not initially called. However, if the value "null" or "false" is provided, then the se ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Comparing Angular 9 Testing: Finding the Best Tool Between Cypress and Selenium with BrowserStack

Currently working with an Angular 9 Nrwl project and looking to incorporate automated testing. I'm torn between using Selenium (Browserstack) or the built-in Cypress tool. Which would be more beneficial for Angular projects, and what are the advantage ...

Executing a Playwright test against various projects or URLs within a single test run

I've been grappling with this problem for the past few days. I've tried a few workarounds, but none of them have worked as expected. What I need is to run Playwright tests against multiple URLs. Currently, running tests in a single project works ...

"Zone has been successfully loaded" - incorporating angular universal ssr

I am currently working on an Angular project and I am looking to implement server-side rendering. To achieve this, I decided to use Angular Universal. The browser module of my project was successfully built, but I encountered the following issue during the ...

Issue encountered while combining TypeScript interface function declarations (Interface Merging)

interface Cat { meow(words: string): string; } interface Cat { meow(num: number): number; } const cat: Cat = { meow(wordsOrNum): string | number { return wordsOrNum; } } In the example code above, interfaces demonstrate how decla ...

What is the method for accessing the string value of a component's input attribute binding in Angular 2?

In my Angular2 application, I have a straightforward form input component with an @Input binding pointing to the attribute [dataProperty]. The [dataProperty] attribute holds a string value of this format: [dataProperty]="modelObject.childObj.prop". The mod ...

Unlike other checkbox components, mat-checkbox does not respond to a false condition unless double-clicked

I am dealing with a situation where an entity has a variable that needs to be the opposite of the checkbox state. enitity.enabled = true The checkbox serves as a way to indicate that an item should be deleted. When the form is submitted, the marked item i ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...