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)
[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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With