2
votes

Here is a part of my html:

<div class="container"> 

And here is the related CSS part:

.container{
width:100%;
height: 45px;}

@media (min-width: 768px) { 
.container{
height:60px;}

Now I want to bind the style of this div to a property by ngStyle. I have a property in app.component.ts called isShrinked, and when isShrinked===true, I would like the height of the div to be 10px, otherwise the height would be the default value set by the css style of container class.

Now I read the Angular documentation about ngStyle but I cannot find the correct syntax to achieve this. The closest I can do is by adding something like[ngStyle]="{'height': isShrinked?'10px':''}" But this obviously does not work as I would have to give a value to the right side in this ternary expression, which is not what I intend to do.

Can somebody help me?

1

1 Answers

4
votes

The following syntaxes should work:

[ngStyle]="isShrinked ? { 'height': '10px' } : {}"
[ngStyle]="isShrinked ? { 'height': '10px' } : null"

If only one style attribute is to be set, the same result can be obtained with this specific style binding:

[style.height.px]="isShrinked ? 10 : null"

See this stackblitz for a demo.