unable to change the background color in Angular using style binding

五迷三道 提交于 2021-02-10 07:27:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!