简体   繁体   中英

How to change the background color using classname in angular 6?

How can I change the background color or image using classname on click ok button.

For Example I have one div,

I can write this code in jquery like this,

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

In Javascript

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

How can I do this is Angular 2 or 4 or 5 or 6?

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

I tried this one. But it is not working. Can anyone please help me todo this?

I think easier way is to declare parameter and use [style.background] :

HTML

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

TS

color:string="your first color"

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

if you want to use class :

HTML

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

TS

color:string=""

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

Css:

.yourClassName{}
<div class="test" #changeClass>
</div>

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

In component

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

@ViewChild('changeClass') elementRef: ElementRef;

constructor(private renderer: Renderer2){}

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

You can do it something like this:

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

Here is Stackblitz working example: Set background color by ClassName Angular (2/4/5/6)

You can also use the className property like this:

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

Now in your CSS file you will need to have a class named active (which then changes the background-color or whatever you wish).

Of course this allows you to make it dynamic for example:

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

Now Angular will look for a property named active in the class of the component. Then this will be converted to a boolean and if this boolean is true the active class is applied, otherwise the disabled.

There are other ways which are in the other answers which are also just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM