如何通过[ngClass]

时间:2019-06-27 18:24:28

标签: javascript css angular

我有2个选项卡,单击一个tab1将显示一个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;
}

1 个答案:

答案 0 :(得分:1)

尝试一下:

HTML

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

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

stackblitz demo