在Angular中将十进制值转换为十六进制值以动态更改background-color
。这是组件
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';
}
}
答案 0 :(得分:2)
您必须将十六进制转换为十进制加/减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)
}
}