首页 > 解决方案 > 如何通过 [ngClass] 清除或删除 Angular 6 中的类

问题描述

我有 2 个选项卡,单击一个选项卡 1 将显示一个 div,再次单击切换按钮,该 div 将通过更改类展开(100% 宽度)和折叠(25% 宽度)。当我再次单击 tab2,然后单击 tab1 时,我的 div 应该始终保持折叠状态,我的意思是它的类应该是“旧的”。这是下面的代码。

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;
}

标签: javascriptcssangular

解决方案


尝试这个:

HTML

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

删除了class="old". 请立即检查。

stackblitz 演示


推荐阅读