首页 文章

Angular2动态更改CSS属性

提问于
浏览
64

我们正在创建一个 Angular2 application ,我们希望能够以某种方式创建一个全局CSS变量(并在分配变量时更改属性的值) .

我们使用了Polymer一段时间(现在我们正在切换到Angular2组件)并且我们使用了CSS属性(Polymer有一些polyfill),我们只使用 Polymer.updateStyles() 更新了样式 .

有什么方法可以实现类似的功能吗?

EDIT:

我们想要类似于Sass color: $g-main-color 的东西或CSS自定义属性 color: var(--g-main-color) ,每当我们决定更改属性的值时,例如像 updateVariable('g-main-color', '#112a4f') 这样的东西动态地更新了 Value . 所有这一切都在应用程序运行时 .

EDIT 2:

我想在我的CSS的不同部分(host,child element ...)中使用一些全局CSS变量,并且能够立即更改值 - 所以如果我更改my-color变量,它会在应用程序的任何位置发生变化 .

我将使用Sass语法为例:

:host { border: 2px solid $my-color }
:host .some-label { color: $my-color }

可以使用Angular管道之类的东西吗? (但它应该只适用于HTML)

:host { border: 2px solid {{ 'my-color' | cssvariable }} }
:host .some-label { color: {{ 'my-color' | cssvariable }} }

5 回答

  • 64

    Just use standard CSS variables:

    你的全局css(例如:styles.css)

    body {
      --my-var: #000
    }
    

    在你的组件的css o中它是什么:

    span {
      color: var(--my-var)
    }
    

    然后,您可以通过将内联样式设置为html元素来直接使用TS / JS更改变量的值:

    document.querySelector("body").style.cssText = "--my-var: #000";
    

    否则你可以使用jQuery:

    $("body").css("--my-var", "#fff");
    
  • 9

    1)使用内联样式

    <div [style.color]="myDynamicColor">
    

    2)使用多个CSS类映射到你想要的并切换类,如:

    /* CSS */
     .theme { /* any shared styles */ }
     .theme.blue { color: blue; }
     .theme.red { color: red; }
    
     /* Template */
     <div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
     <div class="theme" [class.blue]="isBlue">
    

    代码示例来自:https://angular.io/cheatsheet

    有关ngClass指令的更多信息:https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

  • 5

    你没有任何示例代码,但我想你想做这样的事情?

    @View({
    directives: [NgClass],
    styles: [`
        .${TodoModel.COMPLETED}  {
            text-decoration: line-through;
        }
        .${TodoModel.STARTED} {
            color: green;
        }
    `],
    template: `<div>
                    <span [ng-class]="todo.status" >{{todo.title}}</span>
                    <button (click)="todo.toggle()" >Toggle status</button>
                </div>`
    })
    

    您将 ng-class 分配给动态变量(您可以猜测的模型属性为 TodoModel ) .

    todo.toggle() 正在改变 todo.status 的值,并且输入的类正在改变 .

    这是类名的一个例子,但实际上你可以对css属性做同样的考虑 .

    我希望这就是你的意思 .

    这个例子是针对伟大的egghead教程here .

  • 2

    我做了this plunker探索一种方法来做你想做的事 .

    在这里,我从父组件中获取 mystyle ,但您可以从服务获取它 .

    import {Component, View} from 'angular2/angular2'
    
    @Component({
      selector: '[my-person]',
      inputs: [
        'name',
        'mystyle: customstyle'
      ],
      host: {
        '[style.backgroundColor]': 'mystyle.backgroundColor'
      }
    })
    @View({
      template: `My Person Component: {{ name }}`
    })
    export class Person {}
    
  • -2

    Angular 6 + Alyle UI

    使用Alyle UI,您可以动态更改样式

    这里demo stackblitz

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        CommonModule,
        FormsModule,
        HttpClientModule,
        BrowserAnimationsModule,
        AlyleUIModule.forRoot(
          {
            name: 'myTheme',
            primary: {
              default: '#00bcd4'
            },
            accent: {
              default: '#ff4081'
            },
            scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
            lightGreen: '#8bc34a',
            colorSchemes: {
              light: {
                myColor: 'teal',
              },
              dark: {
                myColor: '#FF923D'
              },
              myCustomScheme: {
                background: {
                  primary: '#dde4e6',
                },
                text: {
                  default: '#fff'
                },
                myColor: '#C362FF'
              }
            }
          }
        ),
        LyCommonModule, // for bg, color, raised and others
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    HTML

    <div [className]="classes.card">dynamic style</div>
    <p color="myColor">myColor</p>
    <p bg="myColor">myColor</p>
    

    For change Style

    import { Component } from '@angular/core';
    import { LyTheme } from '@alyle/ui';
    
    @Component({ ... })
    export class AppComponent  {
      classes = {
        card: this.theme.setStyle(
          'card', // key
          () => (
            // style
            `background-color: ${this.theme.palette.myColor};` +
            `position: relative;` +
            `margin: 1em;` +
            `text-align: center;`
             ...
          )
        )
      }
      constructor(
        public theme: LyTheme
      ) { }
    
      changeScheme() {
        const scheme = this.theme.palette.scheme === 'light' ?
        'dark' : this.theme.palette.scheme === 'dark' ?
        'myCustomScheme' : 'light';
        this.theme.setScheme(scheme);
      }
    }
    

    Github Repository

相关问题