简体   繁体   中英

How to clear or remove a class in angular 6 through [ngClass]

I have 2 tabs,onclick a tab1 a div will be shown, again on click toggle button the div will expand(100% width) and collapse(25% width) by changing the class. Again when I click on tab2, and then click on tab1 my div should be remain collapse always,I mean its class should be 'old'.Here is the code below.

app.component.html

<span style="cursor:pointer" (click) = "tab1()">Tab1</span>&nbsp;<span (click) = "tab2()" style="cursor:pointer">Tab2</span>
<div  [ngClass]="{'old': toggle, 'new': !toggle}" *ngIf="show" class="old">
  Hello
</div>
<button (click)="change()">change</button>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toggle:boolean = true;
  show:any;
tab1(){
    alert('tab1');
    this.show = true;
}
tab2(){
    alert('tab2');
    this.show = true;
}
  change(){
    this.toggle = !this.toggle;
  }

  ngOnInit() {
this.show = false;
  }
}

app.component.css

.old{
    width:25%;
    border:1px solid;
    height:200px;
    cursor:pointer;
    background:yellow;
}
.new{
    width:100%;
    border:1px solid;
    height:200px;
    cursor:pointer;
    background:green;
}

Try this:

HTML

<div  [ngClass]="toggle ? 'old' : 'new'" *ngIf="show">
     Hello
</div>

Removed the class="old" . Please check now.

stackblitz demo

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