【问题标题】:Dynamically generating CSS classes at runtime in Angular 7在 Angular 7 运行时动态生成 CSS 类
【发布时间】:2023-03-03 10:31:01
【问题描述】:

我有一个 Angular 7 应用程序,我需要在运行时在我的组件中动态生成 CSS 类。

首先:我知道[ngStyle][ngClass]!我需要使用无法生成的伪选择器来做一些事情。

现在,天真的方法:我将使用 Angular 来模板化我的 CSS!

<style *ngFor="let class of classes">
    .{{class.prefix}}-target {
        border: 1px solid maroon;
        text-align: center;
      }

      .{{class.prefix}}-control:hover ~ .{{class.prefix}}-target {
          background: red;
        }
  </style>

这种方法的问题:

  1. VS Code 抱怨我将 Angular 模板放入 CSS 类中。
  2. Angular 不会在最终生成的 HTML 中插入 {{class.prefix}} - 它只是将 {{class.prefix}} 直接放在那里。

有没有办法在 Angular 中做到这一点,无论是使用为此目的的库还是我可以使用的方法?提前致谢!

【问题讨论】:

    标签: css angular


    【解决方案1】:

    取决于您需要组件的动态程度...

    您可以在组件类之外声明前缀(或动态生成)。然后使用 JavaScript 模板字符串在样式被 @Component() 装饰器的元数据处理之前对其进行解释。

    像这样:

    const classPrefix = 'bar';
    
    @Component({
      selector: 'app-foo',
      template: `
        <!-- Your HTML template -->
      `,
      styles: [`
        .${classPrefix}-target {
            border: 1px solid maroon;
            text-align: center;
        }
        .${classPrefix}-control:hover ~ ${classPrefix}-target {
            background: red;
        }
    `]
    })
    export class FooComponent {
    /* . . . */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-10
      • 2017-04-08
      • 2018-02-13
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多