【问题标题】:Insert dynamic css code into angular component将动态css代码插入角度组件
【发布时间】:2020-11-20 18:24:12
【问题描述】:

我不知道如何将 css 代码插入到我的 Angular 组件中。

let sheet: any = document.createElement('style');
sheet.type = "text/css";
sheet.textContent = `\n @keyframes ${this.config.animationConfig.name} { from { ${this.config.animationConfig.steps[0]} } to { ${this.config.animationConfig.steps[1]} } }`;

最好的问候,感谢您的帮助

乔纳兹

【问题讨论】:

  • 只需将其添加到 html 头。无法将角度封装应用于动态样式,因为它应该发生在项目的编译阶段

标签: angular


【解决方案1】:

这只是一个示例实现 - 可能有更简单/更好的方法来做到这一点,但这对您来说应该是一个很好的起点。

首先,获取对模板中某个元素的引用:

@ViewChild('someDivElement', {static: true}) stylesContainer: ElementRef;

然后,每次您需要重新计算样式时,您都可以这样做:

  private changeStyles(): void {
    const styleContent = this.getSomeStyleContent(); // This should be a string value of what you would put inside the <style> element.

    // Get the native element from the container reference
    const placeholderElement: HTMLDivElement = this.stylesContainer.nativeElement;

    // If there is already element in it, remove it. If you need something else than styles in that component,
    // query the item differently, e.g. by type.
    if (placeholderElement.firstChild) {
      placeholderElement.removeChild(placeholderElement.firstChild);
    }

    // Add your styles inside the placeholder.
    placeholderElement.insertAdjacentHTML('afterbegin', `<style>${styles}</style>`);
  }

请注意,这不是封装的,这意味着它将影响整个站点上的 html,而不仅仅是该组件内。另请注意,它会强制重排(如果有以前的样式,则强制重排),但我们对此无能为力。

【讨论】:

  • 这是否也适用于 Mat-Components,例如
  • 它没有被封装,所以如果你正确地添加样式那么它应该。虽然也许更简单的解决方案是使用 ngStyle、ngClass 或其他方法?
  • 我也考虑过 ngStyle 或 ng Class,但问题是,我想插入 css 关键帧动画,而角度动画系统是基于 js 的,因此速度较慢。
  • 不确定您的用例是什么,而且我不擅长 CSS 和动画,但也许您可以自己利用硬编码动画并仅通过绑定更新 CSS 变量?似乎比将带有样式的容器实际插入模板要干净得多。例如 - 检查这个答案:stackoverflow.com/a/63506012/4550158(如果你还没有使用 Angular 9+,则链接 github 问题 - 认为它有一些解决方法)。
  • 我明白你的意思,但在我们的项目中,客户将处理所有事情,包括关键帧动画的整个结构。这就是为什么我问我如何将 css 动画注入组件的原因,但我的主管对上面的答案很好。感谢您的帮助!
【解决方案2】:

这是否也适用于 Mat-Components,例如

// Get the native element from the container reference
    const placeholderElement: HTMLDivElement = this.stylesContainer.nativeElement;

    // If there is already element in it, remove it. If you need something else than styles in that component,
    // query the item differently, e.g. by type.
    if (placeholderElement.firstChild) {
      placeholderElement.removeChild(placeholderElement.firstChild);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多