【问题标题】:How to change the background color using classname in angular 6?如何使用 Angular 6 中的类名更改背景颜色?
【发布时间】:2019-01-03 06:51:44
【问题描述】:

如何在单击确定按钮时使用类名更改背景颜色或图像。

例如我有一个 div,

我可以像这样在jquery中编写这段代码,

$(".test").css("background","red");

在 Javascript 中

document.getElementByClassName('.test').style.background="red";

Angular 2 或 4 或 5 或 6 我该怎么做?

changebtn():void{
document.querySelector('test').classList.add('newClass');
}
<div class="test">
</div>

<button (click)="changeBtn()"></button>

我试过这个。但它不起作用。谁能帮我做这件事?

【问题讨论】:

标签: html css angular angular5 angular6


【解决方案1】:

我认为更简单的方法是声明参数并使用[style.background]:

HTML

<button (click)="changeBtn()" [style.background]="color"></button>

TS

color:string="your first color"

changebtn(){
 //change to your wanted color
  color="red";
}

如果你想使用class:

HTML

<button (click)="changeBtn()" [class]="color"></button>

TS

color:string=""

changebtn(){
 //change to your wanted color
  color="yourClassName";
}

CSS:

.yourClassName{}

【讨论】:

  • 如何更改边框半径? [style.borderRadius]="3px" 这样对吗?
  • @sathishkumar 不,这是真正的 css 属性,[style.border-radius]。而且你必须输入一个字符串,所以[style.border-radius]="'3px'"
  • @sathishkumar 使用 trichetriche 说的或使用我的编辑(带类)
  • 我建议[style.border-radius.px]="3"。
【解决方案2】:
<div class="test" #changeClass>
</div>

<button (click)="changeBtn()"></button>

在组件中

import { ElementRef, ViewChild, Renderer2 } from '@angular/core';

@ViewChild('changeClass') elementRef: ElementRef;

constructor(private renderer: Renderer2){}

changebtn = () => {
    this.renderer.addClass(this.elementRef.nativeElement, 'new-class');
}

【讨论】:

    【解决方案3】:

    你可以这样做:

    document.getElementsByClassName('test')[0]["style"].background="red";
    

    这是 Stackblitz 的工作示例:Set background color by ClassName Angular (2/4/5/6)

    【讨论】:

      【解决方案4】:

      你也可以像这样使用 className 属性:

      <div [className]="'active'"></div>
      

      现在,在您的 CSS 文件中,您将需要一个名为 active 的类(然后更改背景颜色或您希望的任何内容)。

      当然,这允许您使其动态化,例如:

      <div [className]="active ? active :disabled"></div>
      

      现在 Angular 将在组件的类中查找名为 active 的属性。然后这将被转换为一个布尔值,如果这个布尔值为真,则应用活动类,否则禁用。

      其他答案中还有其他方法也很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-27
        • 2019-04-04
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        相关资源
        最近更新 更多