【问题标题】:how to use ng-deep with dynamic data如何使用 ng-deep 处理动态数据
【发布时间】:2020-06-11 16:33:50
【问题描述】:

我需要为给定的类动态定义字体大小,但它们的值是从服务器获取的。静态看起来像这样:

::ng-deep .text-huge {
   font-size: 2.8em; 
}

我怎样才能将它转换为动态分配的值?

::ng-deep .text-huge {
   font-size: data.fontSize; 
}

感谢您的帮助

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以通过将动态 CSS 直接注入<style> 元素来添加它。

    例子:

    data = { fontSize : '13px' };
    
    const textCss = `::ng-deep .text-huge {
       font-size: ${data.fontSize}; 
    }`
    
    document.getElementsByTagName('style')[0].append(textCss);
    

    注意:上面的代码会将您的 CSS 添加到文档中的第一个样式元素

    或者您可以创建一个样式元素并使用您的动态 CSS 将其直接注入到您的组件中。

    【讨论】:

      【解决方案2】:

      您不能从 TS 中分配 CSS 变量的值。

      Set sass variable value in Angular 7

      您可以在项目中使用 CSS 变量,这些变量会被 TS 文件修改为某个值:

      css:

      ::root {
        --some-var: #fff;
      }
      
      .your-class {
        color: var(--some-var);
      }
      

      在ts中:

      // Assuimg that new value is an HEX color without `#`
      public changeSomeVar(newValue: string): void {
        document.documentElement.style.setProperty('--some-var', #${newValue});
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-28
        • 2017-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-23
        • 1970-01-01
        相关资源
        最近更新 更多