【问题标题】:load style file using bundleName in angular使用bundleName以角度加载样式文件
【发布时间】:2022-02-08 18:56:52
【问题描述】:

我有lightdark 主题文件,并在angular.json 文件中提到如下:

"styles": [
    "src/styles.scss",
    {
       "input": "src/styles/themes/light.theme.scss",
       "bundleName": "light-theme",
       "inject": false
    },
    {
       "input": "src/styles/themes/dark.theme.scss",
       "bundleName": "dark-theme",
       "inject": false
    }
],

我想通过这段代码动态注入每个文件

loadStyle(styleName: string = 'light-theme' | 'dark-theme') {
  const head = this.document.getElementsByTagName('head')[0];

  let themeLink = this.document.getElementById('client-theme') as HTMLLinkElement;

  if (themeLink) {
    themeLink.href = styleName;
  } else {
    const style = this.document.createElement('link');
    style.id = 'client-theme';
    style.rel = 'stylesheet';
    style.href = `${styleName}`;

    head.appendChild(style);
  }
}

以上代码创建链接为

<link id="client-theme" rel="stylesheet" href="dark-theme"> // href="light-theme"

但是什么都没有发生,因为实际的主题文件没有被注入到 head-tag 中。

更新

根据Angular Materialdocs

您可以在单独的文件中定义多个主题,方法是为每个定义主题创建多个主题文件,将每个文件添加到 angular.json 的样式中。但是,您必须另外将每个文件的注入选项设置为 false,以防止同时加载所有主题文件。将此属性设置为 false 时,您的应用程序将负责手动加载所需的文件。此加载的方法取决于您的应用程序。 https://material.angular.io/guide/theming#multiple-themes-across-separate-files

但是在文档中没有加载样式文件的过程:(

任何建议/解决方案都将非常受欢迎!!! :)

【问题讨论】:

    标签: html angular file styles


    【解决方案1】:

    我不认为你可以直接使用 bundleName 作为 href。也许尝试这样的事情:

    style.href = `styles/themes/${styleName}.css`;
    

    【讨论】:

    • 您的解决方案很好,但必须有bundleName 的用例。在一篇文章中,作者说使用 bundleName 来调用样式文件,但在我的情况下它不起作用。
    • 它仍然使用 bundleName,因为 styleName 填充了 dark-theme 而不是 dark.theme。我认为它只是替换文件名而不是整个路径和扩展名。你有文章的链接吗?
    • 这里是链接juristr.com/blog/2019/08/dynamically-load-css-angular-cli,如果你知道我想念的地方,请告诉我。
    • 切换主题时似乎确实添加了扩展名:loadStyle('client-a.css')。该博客将文件放在根文件夹中,这可能解释了为什么您还需要styles/themes..
    猜你喜欢
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2019-05-11
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    相关资源
    最近更新 更多