如何在运行时更改ng-zorro主题

问题描述 投票:0回答:1

我做了很多研究,找不到找到生成ng-zorro主题并在运行时对其进行更改的方法。

最后,我可以找到一种方法来做到这一点。

less angular9 ng-zorro-antd
1个回答
0
投票

该示例适用于在项目中使用.less样式的项目

  1. [首先,您需要通过命令less-plugin-clean-css]安装npm i less -D less-plugin-clean-css -D dev依赖项>

  2. src文件夹中创建theme.less

    文件,其中包含:
  3. @import "../node_modules/ng-zorro-antd/ng-zorro-antd.less";     // this is important
    
    
    @primary-color : #f5222d;       // and define the variables which are uses in the library
    

    这里是完整变量enter link description here的链接

  1. themes文件夹中创建assets文件夹

  2. 定义less-compiler.js其中包含:

  3. const less = require('less');
    const LessPluginCleanCSS = require('less-plugin-clean-css');
    const fs = require('fs');
    const darkThemeVars = require('ng-zorro-antd/dark-theme');
    
    const appStyles = './src/theme.less';    // this path should be the path of the theme.less file
    const themeContent = `@import '${appStyles}';`;
    
    less.render(themeContent, {
      javascriptEnabled: true,
      plugins: [new LessPluginCleanCSS({ advanced: true })],
      modifyVars: {
        ...darkThemeVars
      }
    }).then(data => {
      fs.writeFileSync(
        // output path for the theme style
        './src/assets/themes/style.dark.css', 
        data.css
      )
    }).catch(e => {
      // log the render error
      console.error(e);
    });
    
    1. 在终端中运行node ./less-compiler.js(此命令应在style.dark.css文件夹中生成src/assets/themes文件)

  4. ((可选)

    如果要在每次构建项目时都运行node ./less-compiler.js,则可以在"build": "ng build",中将"build": "ng build && node ./less-compiler.js",替换为package.json,然后可以通过npm run build命令构建项目。
  5. 定义一个可帮助您删除主题链接或将其添加到头部的功能。 (在我的情况下,app.component.ts文件中定义的函数)

  6. // .............
    export class AppComponent {
      theme = '';
      constructor() {
          setInterval(() => {
             this.changeTheme()
          }, 2000);
      }
    
      changeTheme() {
        this.theme = this.theme === 'dark' ? '' : 'dark';
        if (this.theme === 'dark') {
          const style = document.createElement('link');
          style.type = 'text/css';
          style.rel = 'stylesheet';
          style.id = 'dark-theme';
          style.href = '/assets/themes/style.dark.css';
          document.head.appendChild(style);
        } else {
          const dom = document.getElementById('dark-theme');
          if (dom) {
            dom.remove();
          }
        }
    
      }
    }
    

    我希望这可以帮助您轻松组织运行时主题切换。

© www.soinside.com 2019 - 2024. All rights reserved.