Angular 6 set Background Color in Html to CSS Variable

后端 未结 3 484
离开以前
离开以前 2021-01-18 08:37

I am using Angular 6 and I have a simple div and want to set the background color of this div from inside the template. This works fine when passin

相关标签:
3条回答
  • 2021-01-18 09:11

    You have to use ngStyle

    <some-element [ngStyle]="{'background-color': styleExp}">...</some-element>
    

    https://angular.io/api/common/NgStyle

    0 讨论(0)
  • 2021-01-18 09:20

    You can do it in 2 ways

    1. use pipe that get a string and return some color code code.

      <div [style.background-color]="someString | colorSetter"></div>
      
    2. add to the html tag a dynamic class for example:

      <div class="my-div" [class]="someClassName"></div>

    and in the scss add the options

    scss:

    .my-div{
        &.optoin1{
           background-color:red;
         }
    &.optoin2{
           background-color:black;
         }
    &.optoin3{
           background-color:green;
         }
    &.optoin4{
           background-color:yellow;
         }
    }
    
    0 讨论(0)
  • 2021-01-18 09:35

    In order to bind a style property to a CSS variable in the HTML template, the CSS variable expression var(...) must be sanitized. You can define a custom pipe:

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
    
    @Pipe({
      name: 'safeStyle'
    })
    export class SafeStylePipe implements PipeTransform {
    
      constructor(private sanitizer: DomSanitizer) { }
    
      transform(value: string): SafeStyle {
        return this.sanitizer.bypassSecurityTrustStyle(value);
      }
    }
    

    and use it in the HTML template:

    <div [style.background-color]="'var(--some-css-var)' | safeStyle"></div>
    <div [style.background-color]="bkColor | safeStyle"></div>
    
    bkColor = "var(--some-css-var)";
    

    See this stackblitz for a demo.

    0 讨论(0)
提交回复
热议问题