3

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)

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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>

1 Comment

yes, great but what if I want to modify col number via @Input() ? As I've mentioned, parameter / configuration should come dynamically, so it can be col-8, col-4, col-2 etc.
1

even i put false : [attr.col-12]='false' the arribute is set to the tag. I work with angular4/ionic3

1 Comment

See the answer of cyptus. For the attribute to be removed, the expression has to evaluate to null. stackoverflow.com/a/45236859/3764913

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.