如何根据Angular中的按钮类更改点击功能

在 Angular 中,我有一个切换类的按钮 - 我想要做的是基于按钮类添加事件。这应该通过If函数中的语句来完成吗?到目前为止,我的代码如下:


HTML 按钮


<!-- toggle button --> 

<button type="button" class="btn btn-primary mt-3 ml-3 btn-button" (click)="status=!status; func()" [ngClass]="{'btn-danger' : status, 'btn-primary' : !status}"  [disabled]="clicked">{{status ? 'Delete' : 'Add'}}</button>

<!-- toggle button -->

组件.ts


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


@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})


export class AppComponent {


public btn: any;


func () {

   if (this.btn.hasClass('btn-primary')) {

      alert('Primary clicked');    

   } else if (this.btn.hasClass('btn-danger')) {

     alert('Danger clicked');    

   }

 }

}


慕神8447489
浏览 144回答 3
3回答

POPMUISE

status您可以检查值而不是类名。试试这样:工作演示.html(click)="func()".ts&nbsp; func() {&nbsp; &nbsp; this.status = !this.status;&nbsp; &nbsp; if (this.status) {&nbsp; &nbsp; &nbsp; alert("Primary clicked");&nbsp; &nbsp; } else if (!this.status) {&nbsp; &nbsp; &nbsp; alert("Danger clicked");&nbsp; &nbsp; }&nbsp; }

红糖糍粑

你可以看看这个演示可能对你有帮助action您可以更改财产基础课程;<button (click)="onClick()" [ngClass]="action =='Add' ? 'btn-primary': 'btn-danger'"> {{action}}</button>点击按钮&nbsp;onClick() {&nbsp; &nbsp; if(this.action == 'Add') {&nbsp; &nbsp; &nbsp; this.action = 'Delete';&nbsp; &nbsp; &nbsp; alert('Primary Clicked');&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; this.action = 'Add';&nbsp; &nbsp; &nbsp; &nbsp; alert('Danger clicked');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; }

繁花如伊

怎么样:<button id="myBtn" type="button" class="btn btn-primary" (click)="func()">{{buttontext}}</button>TSbuttontext: string = 'ADD';func () {&nbsp; &nbsp; let element = document.getElementById("myBtn");&nbsp; &nbsp; element.classList.toggle("btn-danger");&nbsp; &nbsp; element.classList.toggle("btn-primary");&nbsp; &nbsp; this.buttontext = this.buttontext === 'ADD' ? 'DELETE' : 'ADD';}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript