如何在单击时更改按钮类

时间:2019-11-29 14:47:02

标签: angular bootstrap-4

我有2个按钮,并且我想通过更改按钮类别来显示活动按钮。我正在尝试通过removeClass && addClass做。遇到错误

  

removeClass不是函数

.component.html

true

.component.ts

<div class="col" id="but">
  <button #draw id="draw" class="btn btn-success" (click)="DrawSketch(draw)">Draw Sketch</button>

  <button #upload id="upload" class="btn bg-gradient-white" (click)="UploadSketch(upload)">Upload Sketch</button>
</div>

<div>{{activeButton}}</div>

这里是stackblitz link

如何执行此操作?我在哪里做错了?

请提出是否还有更好/其他方法。

2 个答案:

答案 0 :(得分:1)

您可以使用ngClass动态添加或删除类。

在.component.ts中

   uploadId: any;
  drawId: any;
  activeButton:string = 'Draw'; // Set the draw button by default as activeButton

  DrawSketch(button){
    this.drawId = button.id;
    console.log("DrawSketch called...",this.drawId);   
    this.activeButton = "Draw";
  }

  UploadSketch(button){
    this.uploadId = button.id;
    console.log("UploadSketch called...", this.uploadId);
    this.activeButton = "Upload";
  }

在.component.html

<div class="col" id="but">
  <button #draw id="draw" class="btn" [ngClass]="{ 'btn-success': activeButton === 'Draw', 'bg-gradient-white': activeButton !== 'Draw'}" (click)="DrawSketch(draw)">Draw Sketch</button>

  <button #upload id="upload" class="btn" [ngClass]="{ 'btn-success': activeButton === 'Upload', 'bg-gradient-white': activeButton !== 'Upload'}" (click)="UploadSketch(upload)">Upload Sketch</button>
</div>

<div>{{activeButton}}</div>

答案 1 :(得分:0)

我不确定您要实现的目标,但是我有一个link,如果您需要更改CSS,可以使用它。例如,如果我需要根据特定条件在按钮上应用不同的CSS类,我将执行以下操作:

    <button [ngClass]="{
    'removeClass':Condition === '1stOption',
    'addClass':Condition === '2ndOption',
    'defaultClass':Condition === 'defaultOption'
  }"> Button content </button>

我希望它可以帮助... 在此处检查工作:Working Code