问题
The background color of the div
is not changing when using the style binding using Angular.The code is placed below for reference
@Component({
selector: 'course',
template: `
<div [style.backgroundColor]='red'>
<button (click)="onClick($event)" class="btn btn-primary" [class.active]="isActive" [style.backgroundColor]='red'>Save</button>
</div>
`,
styleUrls: ['./course.component.css']
})
export class CourseComponent {...}
The style element has the backgroundColor
property. Where am I going wrong?
回答1:
Angular property binding expects an expression instead of a value which you are trying to assign.
Instead of [style.backgroundColor]='red'
you might want to use [style.backgroundColor]="'red'"
note that i have wrapped 'red' on quotes.
回答2:
You need to use [ngStyle]
with backgroundColor
property
<div [ngStyle]="{backgroundColor: 'red' }">
<button (click)="onClick($event)" class="btn btn-primary" [class.active]="isActive" [ngStyle]="{backgroundColor: 'red' }">Save</button>
</div>
DEMO STACKBLITZ
回答3:
I think you've a typo in your code ..
try this:
[style.background-color]="'red'"
.. so something like:
@Component({
selector: 'course',
template: `
<div [style.background-color]='red'>
<button (click)="onClick($event)" class="btn btn-primary" [class.active]="isActive" [style.background-color]='red'>Save</button>
</div>
`,
styleUrls: ['./course.component.css']
})
export class CourseComponent {...}
Hope it helps you!
来源:https://stackoverflow.com/questions/48850525/unable-to-change-the-background-color-in-angular-using-style-binding