动态添加 div 属性值

Add div attributes value dynamically

我想在 Angular 中动态添加 div 属性 7.

我试过这个:

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

我有这个错误:

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

当你动态循环时,你应该使用这样的东西:

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

你有几个选择:

  1. <div attributeName="{{attributeValue}}"/></div>
  2. <div [attr.attributeName]="attributeValue"/></div>
  3. <div [attr.attributeName]="getAttributeValueFun()"/></div>

您要实现的目标是 Attribute Binding。正如官方文档所说:

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

所以,据此,您需要稍微更改一下代码。对于 style,您可以使用 ngStyle[style.background],但 !important 在其中不起作用:

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