【问题标题】:How to change/toggle class of a div on click a button in angular 6如何在单击角度 6 中的按钮时更改/切换 div 的类
【发布时间】:2019-09-22 22:52:23
【问题描述】:

这里我有一个 div,其类名为 old。我还有一个按钮 onchange/toggle 我需要将 div 的 类名更改为 new。再次单击按钮我需要更改类div 到.so on.. 角度为 6。这是下面的代码,

其实我是 Angular 6 的新手,谁能帮帮我。

app.component.html

<button (click)="change()">change</button>
<div class="old">
  Hello
</div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  change(){
    alert('change');
  }

  ngOnInit() {

}
}

【问题讨论】:

    标签: html angular


    【解决方案1】:

    您可以使用布尔变量和ngClass 指令来实现。

    模板:

    <button (click)="change()">change</button>
    <div [ngClass]="{'old': toggle, 'new': !toggle}"class="old">
      Hello
    </div>
    

    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;
    
    
      change(){
        this.toggle = !this.toggle;
      }
    
      ngOnInit() {
    
      }
    }
    

    Stackblitz Demo

    【讨论】:

      猜你喜欢
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2023-01-20
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多