Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - add HTML attributes and classes dynamically

Could you please help me to find an answer of how to dynamically add an attribute && class to the HTML template in Angular 2?

Eg.:

<div class="some-class class-8" col-8></div>

8 in above example should come from configuration property, but if specific property is not defined, then col- and class- shouldn't be injected.

Please do not point out that this type of attribute is a bug (this case occurs in Ionic2)

like image 759
user3844198 Avatar asked Dec 17 '25 21:12

user3844198


2 Answers

[attr.col-8] is the right syntax, but the condition should return empty string (true, attribute is set) or null (false, attribute is not set). For example:

[attr.col-6]="field.width == 6 ? '' : null"

does work fine. (i am working with ionic 3)

like image 125
cyptus Avatar answered Dec 20 '25 12:12

cyptus


For dynamic classes you can use this :

<div [ngClass]="{'some-class': true, 'class-8': true}">...</div>

For attribute you can use ::

<div [attr.col-8]='true' > </div>

Here true/false are Boolean values , so you can set conditions also , to add class/attribute when some condition satisfied.

If you want to modify col number via @Input()

@Input(dynamicVar)dynamicVar:String;
<div {{ dynamicVar !== '' ? 'col-'+dynamicVar : '' }} > </div>
like image 28
Vivek Doshi Avatar answered Dec 20 '25 13:12

Vivek Doshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!