2017-04-18 99 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

完美。謝謝。 –