首页 > 解决方案 > 动态改变Angular中元素的宽度

问题描述

原谅我,我是 Angular 的新手。

我试图在单击按钮时动态更改 div。我试过[style.width][style.width.px]. 并且它最初似乎可以设置值,但是当我尝试在函数中更改它时,它似乎没有在屏幕上呈现。意思是,它在 html 中发生了变化,但在视觉上没有变化。我一直盯着这个太久了,所以一些 hep 将不胜感激。

html中的div

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

在 ts 文件中设置初始变量的位置

 logoWidth = '450px';

以及ts文件中的函数

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

标签: cssangular

解决方案


您可以使用ngStyle

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

甚至[style.width需要工作,这;可能会导致问题,因此请将其删除并尝试。

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

或者,您可以提供像素值绑定style.width.px

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

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

推荐阅读