Angular2 dynamic change CSS property

前端 未结 5 1346
粉色の甜心
粉色の甜心 2020-12-01 02:07

We are making an Angular2 application and we want to be able to somehow create a global CSS variable (and update the properties\' values whenever changed wh

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 02:39

    Angular 6 + Alyle UI

    With Alyle UI you can change the styles dynamically

    Here a 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

    dynamic style

    myColor

    myColor

    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

提交回复
热议问题