在 Angular 7 中在运行时动态生成 CSS 类

cai*_*lin 5 css angular

我有一个 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>
Run Code Online (Sandbox Code Playgroud)

这种方法的问题:

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

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

Dal*_*ris 0

根据您需要组件的动态程度...

您可以在组件类之外声明前缀(或动态生成它)。然后使用 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 {
/* . . . */
}
Run Code Online (Sandbox Code Playgroud)