Geoff
Geoff

Reputation: 6629

Angular2 assign style dynamically

I would like to assign style in a th dynamically in Angular 2.

I tried the following:

<th [ngStyle]="{'width:25%': col.field != 'email'}"
    *ngFor="let col of cols"
    [pSortableColumn]="col.field">
        {{col.header}}
</th>

But the above fails.

How should I assign the style property?

Upvotes: 0

Views: 701

Answers (2)

Nabin Paudyal
Nabin Paudyal

Reputation: 1639

You have done it incorrectly. The correct way to do it is:

<th [ngStyle]="{'width': col.field != 'email' ? '25%': auto}"
        *ngFor="let col of cols"
        [pSortableColumn]="col.field"
>
  {{col.header}}
</th>

Upvotes: 2

Armen Vardanyan
Armen Vardanyan

Reputation: 3315

You are misusing the [ngStyle] directive. It does not work like the [ngClass] directive, (adding or removing a css class based on condition). It rather assigns a certain style to the elements CSSStyleDeclaration property, so you should manage dynamic styles maually, like this, in your example:

<th *ngFor ="let col of cols" [ngStyle]="{'width': col.field != 'email' ? '25%': 'auto'}"> // etc

As you seem, I used ternary operator to assign a style dynamically. You can also do this:

<th *ngFor ="let col of cols" [style.width]="col.field != 'email' ? '25%': 'auto'"> // etc

Which is obviously shorter. And, by the way, *ngFor as a property should come before you use the iteration variable among other attributes/directives on the same element (*ngFor and only then [ngStyle], as you use the col variable declared in *ngFor inside the [ngStyle] directive, not the other way round)

Upvotes: 1

Related Questions