Skip to content Skip to sidebar Skip to footer

How To Change An Element’s Css Class And Remove All Other Classes On Click

How do I handle a case in AngularJS 2 where on click of an element it needs to change its own style, and if other elements have that style they need to have it removed — preferab

Solution 1:

The easiest fix to your problem is to assign a unique ID to each included element together with employing another variable to hold selected ID. The logic to turn on my-class CSS class will now be based on the selected ID.

Your new HTML template:

<div (click)="toggleHighlight(1);" [ngClass]="{'my-class': highlightedDiv === 1}">
  > I'm a div that gets styled on click
</div>

Your toggleHighlight function:

highlightedDiv: number;

toggleHighlight(newValue: number) {
  if (this.highlightedDiv === newValue) {
    this.highlightedDiv = 0;
  }
  else {
    this.highlightedDiv = newValue;
  }
}

Working Plnk: https://plnkr.co/edit/fNoXWhUhMaUoeMihbGYd?p=preview

Solution 2:

One solution which worked for me in showing the active menu is using typescript variable name in class as in

class="{{ text1Class }}"

and assign the class name in typescript.

this.text1Class = "active";

or

this.text1Class = "inactive";

You need to have different style class like this

.inactive {
     background-color : gray;
     padding : 10px;
}
.active {
      background-color : green;
      padding : 10px;
}

Assign the class name inside the function

textOneClicked() : void {
    this.text1Class = "active"; // set the active classthis.text2Class = this.text3Class = this.text4Class = "inactive"; // reset other classes
}

A working Plunker here

Solution 3:

I have one hard solution to this problem:

<div (click)="onclick($event);" >
    > I'm a div that gets styled on click
  </div>

app:

classApp {
constructor() {
}
onclick(event){
    var l = event.target.parentElement.getElementsByClassName("my-class");
    var count = l.length;
    for(var i=0;i<count;i++){
    l[i].className = "";
}
event.target.className = "my-class";
}
}

Plink: https://plnkr.co/edit/RHqL56GrTiV9olYE1Ars?p=preview

Solution 4:

Html code

<div [ngClass]="'first-div'"><h2 [ngClass]="'heading'">Log In</h2><div [ngClass]="content"><inputtype="text"placeholder="Enter User Name"name="username"id="username"#usernameclass="in-cl"><iclass="fa fa-user fa-edited"aria-hidden="true"></i><inputtype="{{isPassword ? 'password':'text'}}"placeholder="Password"name="password"id="mypassword" #passwordclass="in-cl"><iclass="fa fa-lock fa-lock-edited"aria-hidden="true"id="lock-id" (click)="onclick()"></i><buttontype="button"class="in-cl" (click)="credential(username.value,password.value)" >SIGN IN</button></div><divclass="forgot"><ahref="#">Forgot Password?</a></div></div>

css code

.first-div{
    width: 350px;
    border: 2px solid black;
    margin-left: auto;
    margin-right: auto;
    margin-top: 130px;
    border-radius: 5px;
    height: 400px;
    background-color: black;
    color: white;

}
.heading{
    color: white;
    text-align: center;
    font-weight: 500;
    /* background-color: white; */   
}
.in-cl{
    margin: 20px20px0px20px;
    border: 2px solid white;
    border-radius: 15px;
    height: 40px;
    padding: 5px;
    width: 300px;
    outline: none;
    color: black;
    /* padding-right: 60px; */
}
::placeholder{
    color: black;
}
divbutton{
    background-color: #3aafa9;
    color:black;
    text-align: center;
    border: none;
}
.forgot{
    margin: 15px;
    text-align: center;
    font-weight: 550;
    color: white;
}

/* .image{
    position: absolute;
    left: 825px;
    top: 222px;
}
.lock-image{
    position: absolute;
    left: 825px;
    top: 282px;
} *//* edited */.fa-user:before{
    color: black;
}
.fa-lock:before{
    color: black;
} 
.fa-unlock:before{
    color: black;
}
.fa-edited{
    top: 228px;
    left: 770px;
    position: absolute;
    width: 28px;
}
.fa-lock-edited{
    top: 287px;
    left: 772px;
    position: absolute;
}
a{
    color: white;
}

ts code

import { Component, OnInit } from'@angular/core';
import { Router } from'@angular/router';
import swal from'sweetalert2';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
exportclassLoginComponent{
  username:string="pavithra";
  password:string="8792415337abcd";
  p = document.getElementById('mypassword');

  constructor(private router:Router) {}
  credential(username:string,password:string){

    if(this.username==username && this.password==password ){
      this.router.navigate(['/home'])
      swal.fire({title:'Signed in successfully', confirmButtonColor:'#3aafa9', type:'success'})
    }
    else{
      this.router.navigate(['/login'])
      swal.fire({title:'Invalid Username or Password',type:'warning',position:'top-end'})

    }
  }
  isPassword = true;
  onclick(){
    let body = document.getElementById('lock-id')
    if (body.classList) { 
      body.classList.toggle("fa-unlock");
      this.isPassword = !(this.isPassword);
    } else {
      var classes = body.className.split(" ");
      console.log(classes)
      var i = classes.indexOf("fa-lock");

      if (i >= 0) 
        classes.splice(i, 1);
      else 
        classes.push("fa-unlock");
        body.className = classes.join(" "); 
    }


  }




}

Post a Comment for "How To Change An Element’s Css Class And Remove All Other Classes On Click"