首页 > 解决方案 > ngStyle 函数在条件下运行

问题描述

我有一个我希望通过 ngStyle 加载的 css 样式列表和 ngStyle 中的一个函数。但是,我只希望函数在值为真时运行,如果不是,则根本不运行。我知道我可以运行该函数并返回一个空值,但使用正确的标记我可以节省运行它的需要。

我一直在函数中做条件逻辑。

<h2[ngStyle]="setStyles(h2)">H2 Content</h2>

<h5[ngStyle]="setStyles(h5)">H5 Content</h2>

在我的 .ts 文件中

let ifPrint = true;

let style = {
   'h2' : {'font-size' : '16px', 'font-weight' : '600'},
   'h5' : {'font-size' : '12px', 'font-weight' : '400'},
   'default' : {}
  }

setStyles(tag){
return ifPrint ? style[tag] : style['default']; 
)};

我想要类似的东西

<h2[ngStyle]="ifPrint ? setStyles(h2) : noneedtorunfunction ">H2 Content</h2>

我需要在 noneedtorun 函数中放置什么才能使其正常工作?

标签: angular

解决方案


将其声明为全局变量。然后ifPrint是 true 或 false 将切换字体大小。

控制器

  public style = {
   'h2' : {'font-size' : '44px', 'font-weight' : '600'},
   'h5' : {'font-size' : '12px', 'font-weight' : '400'}
  };

模板

<h2 [ngStyle]="ifPrint ? style['h2'] : null">H2 Content</h2>

我认为这就是您正在寻找的东西,或者是我能得到的最接近的东西。


推荐阅读