1

Forgive me, I'm new to Angular.

I'm trying to dynamically change the a div when a button is clicked. I have tried [style.width] and [style.width.px]. and it seems to work initially setting the value, but when I try to change it within a function it doesn't seem to be rendering on the screen. Meaning, it changes in the html, but not visually. I have been staring at this too long so some hep would be appreciated.

The div in the html

<div class='logo-contain' [style.width]='logoWidth'>stuff</div>

Where the initial variable is set in the ts file

 logoWidth = '450px';

And the function within the ts file

closeSideMenu(){
    if(my conditional){
        this.logoWidth = '50px;'
    }else{
        this.logoWidth = '250px;'
    }
  }
4
  • it will be always true :( Commented Mar 27, 2020 at 17:02
  • @xdeepakv, yes I just replaced. my real conditional with that. I'll replace it to just say conditional Commented Mar 27, 2020 at 17:03
  • Try with this.logoWidth = '250px';. The semi-colon should not be included in the string. Alternatively, use [style.width.px]="logoWidth", with this.logoWidth = 250;. There is no reason to use [ngStyle] to set a single style property. Commented Mar 27, 2020 at 17:09
  • The [style.width] notation should work. Can you provde a stackblitz of the problem? How do you call closeSideMenu? Commented Mar 27, 2020 at 17:18

2 Answers 2

4

You can use ngStyle

<div class='logo-contain' [ngStyle]='{ width : logoWidth }'>stuff</div>

Even [style.width need to work, that ; may cause the problem so remove it and try.

closeSideMenu(){
    if(my conditional){
        this.logoWidth = '50px'
    }else{
        this.logoWidth = '250px'
    }
  }

Or alternately you can provide pixel value binding style.width.px

<div class='logo-contain' [style.width.px]='logoWidth'>stuff</div>

closeSideMenu(){
    if(my conditional){
        this.logoWidth = 50
    }else{
        this.logoWidth = 250
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Is there a reason why ngStyle works in the case and not style.width?
@zazvorniki : try [style.width.px] ="logoWidth" and value without px, like logoWidth = 50'
0

the issue with value: by mistake u added semi-colon ; at end of the value, 50px; remove ';'. Best use, [ngStyle]

closeSideMenu(){
    if(my conditional){
        this.logoWidth = '50px;'
    }else{
        this.logoWidth = '250px;'
    }
  }

3 Comments

Even with removing that it didn't want to change. Not really sure why. The ngStyle seems to wok though :)
I thinks than u doing something fisshy :-D

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.