htmlcssangularng-style

NgStyle doesn't apply with condition?


Can anyone tell my this works

[style.height]="events?.length === 0 ? 'calc(100vh - 105px)' : null"

but this doesn't?

[ngStyle]="{'height: calc(100vh - 105px)': events?.length === 0 }"

or this?

[style.height]="{'calc(100vh - 105px)': events?.length === 0 }"

Solution

  • On ngStyle, you need to put the style attribute with values as json data. On that json data, the key should style name and the value should be the css attribute value as follows.

    [ngStyle] = "{ 'height': events?.length === 0 ? 'calc(100vh - 105px)' : null }"
    

    But on your code,

    [ngStyle]="{'height: calc(100vh - 105px)': events?.length === 0 }"
    

    You have put the full [style name]: [style value] as the key on json data and it won't work on ngStyle.

    And [style.height] indicates the height css attribute on style html attribute. So [style.height]="'100px'" has the same meaning with style="height: 100px;".

    And on this code,

    [style.height]="{'calc(100vh - 105px)': events?.length === 0 }"
    

    You have put json object into style.height and this is not acceptable as height css attribute value so it's not working.