0

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?

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.