0

I want to add div attributes dynamically in Angular 7.

And I tried this:

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

And I have this error:

Uncaught 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}"

5
  • I'm using angular7 Commented Feb 6, 2019 at 6:05
  • use this {{e.nom}} instead of {{e.nom}" Commented Feb 6, 2019 at 6:07
  • 1
    use [attr.data-code]="e.id" and [attr.data-bg]="e.codeCouleur" instead of data-code="{{e.id}}" data-bg="{{e.codeCouleur}}" Commented Feb 6, 2019 at 6:08
  • Thanks @CruelEngine, it's works. But how can i resolve the style="..." ? Commented Feb 6, 2019 at 6:14
  • 1
    [style.background]="e.codeCouleur" Commented Feb 6, 2019 at 6:16

3 Answers 3

4

You have few options:

  1. <div attributeName="{{attributeValue}}"/></div>
  2. <div [attr.attributeName]="attributeValue"/></div>
  3. <div [attr.attributeName]="getAttributeValueFun()"/></div>
Sign up to request clarification or add additional context in comments.

1 Comment

1 does not seem to work, but 2 is fine
3

When you're looping dynamically you should make use of something like this:

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

Comments

3

The thing you're trying to achieve is called Attribute Binding. As the official document says:

You must use attribute binding when there is no element property to bind.

So, according to that, you need to change the code a little bit. For style, you can use ngStyle or [style.background], but !important won't work in it:

<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.