1
votes

I developed two columns, both with several buttons. The goal is to click on each button, change the background color and the font color of that button.

At an early stage you have all the buttons in their natural state. By clicking on a button in the left column (A, B, C) I want only that button to change the background color and the font color, the same with the buttons in the right column.

Is there also a way that whenever you click on a button in the left column, if in the right column any button has a background color (has already been clicked) it will return to its original state?

I tried to use jquery and work with ID's and class's, but it doesn't seem the most correct way.

Can someone help me?

DEMO

HTML

<div class="row">
    <div class="col">
        <div *ngFor="let item of Groups">
            <button (click)="Change(0,item)" class="btnGrup">{{item.name}}</button>
        </div>
    </div>
    <div class="col">
        <div *ngFor="let item of Words">
            <button (click)="Change(1,item)" class="btn2">{{item.name}}</button>
        </div>
    </div>
</div>

TS

 Change(index, data) {
    let self = this;
    switch (index) {
      case 0:
        // $(".btnGrup").css({ "background-color": "#f7f7f9", "color": "#BCBCCB" });
        // $(".btnGrup").css({ "background-color": "rgba(73, 129, 194, 0.1)", "color": "rgba(73, 129, 194, 1)" });
        break;
      case 1:
        //      $(".btn2").css({ "background-color": "#f7f7f9", "color": "#BCBCCB" });
        // $(".btn2").css({ "background-color": "rgba(73, 129, 194, 0.1)", "color": "rgba(73, 129, 194, 1)" });
        break;
    }
  }
1
why don't you create classes for active and normal state of the buttons,? you can then simply toggle the classes. - Amit Pandey
@AmitPandey the active class should not work because I intend that when clicking it is always "active" and not just and just click - Steve Mc

1 Answers

1
votes

just add a new property to your group, e.g. called it "check"

Groups=[{
  id:1,
  name:"A",
  check:false
},
{
  id:2,
  name:"B",
  check:false
},
...
]

Create two class

.class1
  {
     background-color: #f7f7f9;
   color: #BCBCCB 
   }
.class2
{
  background-color: rgba(73, 129, 194, 0.1);
  color: rgba(73, 129, 194, 1)
}

And use ngClass

<button (click)="item.check=!item.check" 
         class="btnGrup"
         [ngClass]="{'class1':item.check,'class2':!item.check}"
       >{{item.name}}</button>

If you want only one button you needn't add a new property to your "groups", only need two variables

buttonSelect1=-1
buttonSelect2=-1

And use

<div *ngFor="let item of Groups;let i=index">
            <button (click)="buttonSelect1=i" 
               class="btnGrup"
               [ngClass]="{'class1':buttonSelect1==i,'class2':buttonSelect1!=i}"
             >{{item.name}}</button>
</div>