2017-04-18 94 views
1

如何更改背景颜色以十六进制动态角度?如何在Angular2中动态改变背景颜色?

转换十进制值十六进制值的角度来改变背景颜色动态

import { Component } from '@angular/core'; 

    @Component({ 
     selector: 'my-app', 
     template: ` 

     <h1>Change Background Color Dynamically</h1> 

     <!-- Chang Background Color By Increasing Or Decreasing Color Value --> 
     <button (click)="bgColor = bgColor + 15">+</button> 
     <button (click)="bgColor = bgColor - 15">-</button> 

     <div [ngStyle]="{'background-color': '#' + bgColor}"> 
      Changable Background Color 
     </div> 

     ` 
    }) 

    export class AppComponent { 

     bgColor; 

     constructor() { 
     this.bgColor = 'BBFFFF'; 
     } 

    } 

回答

1

你必须转换十六进制到十进制加/减15,然后转换为回十六进制:

plunker:https://plnkr.co/edit/e4Vl9amWbLsE46Aeam4s?p=preview

@Component({ 
    selector: 'my-app', 
    template: ` 
    <h1>Change Background Color Dynamically</h1> 

    <!-- Chang Background Color By Increasing Or Decreasing Color Value --> 
    <button (click)="add()">+</button> 
    <button (click)="subtract()">-</button> 

    <div [ngStyle]="{'background-color': '#' + bgColor}"> 
     Changable Background Color 
    </div> 
    `, 
}) 
export class App { 
    bgColor: string; 
    constructor() { 
    this.bgColor = 'BBFFFF'; 
    } 
    toHex(decimalNum){return decimalNum.toString(16); } 
    toDecimal(hexString){return parseInt(hexString, 16);; } 

    add(){ 
    var decimalPlus15 = this.toDecimal(this.bgColor) + 15; 
    this.bgColor = this.toHex(decimalPlus15) 
    } 
    subtract(){ 
    var decimalPlus15 = this.toDecimal(this.bgColor) - 15; 
    this.bgColor = this.toHex(decimalPlus15) 
    } 
} 
+0

完美。谢谢。 –