如何在单击时更改元素的CSS类并删除所有其他类

12

在AngularJS 2中,当单击元素时需要更改其自身样式,并且如果其他元素具有该样式,则需要将其删除 - 最好在一个函数中处理。类似于Angular.js如何在单击时更改元素的CSS类并删除所有其他元素,只不过使用TypeScript。

组件

https://plnkr.co/edit/Q2BoU4sNnXdaJB5vrZ8h?p=preview

//our root app component
import { NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I'm a div that gets styled on click
      </div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I also want to be styled but only when Im clicked
      </div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > When one of us gets clicked the we want to be the only one with the style all others go back to normal
      </div>
       <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I'm just here cause my creator likes even numbers
      </div>
    </div>
  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
class App {
  isClassVisible: false;

  constructor() {
  }

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

使用Harry的答案添加了一些功能 https://plnkr.co/edit/z9PoHsPsc3k2dKzUH7zi?p=info - BlunderCode
4个回答

22

解决您的问题最简单的方法是为每个包含元素分配一个唯一的ID,并使用另一个变量来保存所选的ID。打开 my-class CSS类的逻辑现在将基于所选的ID。

您的新HTML模板如下:

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

你的toggleHighlight函数:

highlightedDiv: number;

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

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


使用类似的逻辑,我如何进行多选? - Timur
@Timur,多选与单选的工作方式非常不同。您无法制定通用规则来告诉何时关闭先前选择的元素(例如在进行x或y次选择后应该这样做),或者遇到第一个条件时应关闭哪个元素(我应该关闭我选择的第一个元素还是最低价值的元素等)。 - Harry Ninh

3

对于显示当前菜单,我遇到的一个解决方案就是在类中使用typescript变量名,如下:

class="{{ text1Class }}"

在 TypeScript 中分配类名。

this.text1Class = "active";

或者

this.text1Class = "inactive";

您需要像这样拥有不同的样式类:

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

在函数内部分配类名

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

A working Plunker here


2

我有一个较为困难的解决方案:

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

应用:

class App {
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

{{链接1:Plink:https://plnkr.co/edit/RHqL56GrTiV9olYE1Ars?p=preview}}


不错的解决方案。我有点喜欢它,因为它不会切换类。 - dtechplus
实际上,这并不是一个好的解决方案。Angular 的部分目的就是避免直接操作 DOM。 - Greg

1
Html code

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

    </div>
    <div class="forgot">
      <a href="#">Forgot Password?</a>
    </div>  

</div>

CSS代码

.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: 20px 20px 0px 20px;
    border: 2px solid white;
    border-radius: 15px;
    height: 40px;
    padding: 5px;
    width: 300px;
    outline: none;
    color: black;
    /* padding-right: 60px; */
}
::placeholder{
    color: black;
}
div button{
    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 代码

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']
})
export class LoginComponent{
  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(" "); 
    }


  }




}

欢迎来到StackOverflow。请尽量清晰地解释为什么这是问题的答案。 - Jeroen Heier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接