Selected Button State - 1

by black strings

HTML

<div class="container">
   <div id="btn1" class="btn" onClick="comp.onBtnClick(0)">button 1</div>
   <div id="btn2" class="btn" onClick="comp.onBtnClick(1)">button 2</div>
   <div id="btn3" class="btn" onClick="comp.onBtnClick(2)">button 3</div>
</div>

<div class="sub-container">
   <div id="btn4" class="btn">sub buttons 1</div>
   <div id="btn5" class="btn">sub buttons 1</div>
   <div id="btn6" class="btn">sub buttons 1</div>
</div>

SCSS

.container {
  display: flex;
  gap: .5rem;
}

.sub-container {
  display: flex;
  margin-top: 1rem;
  .btn {
    font-size: .9rem;
    padding: 5px;
    display: block;
    width: 100%;
  }
}

.btn {
  cursor: pointer;
  user-select: none;
  border: thin solid grey;
  width: 100px;
  padding: .5rem;
  border-radius: 1rem;
  &:hover {
    background-color: green;
  }
}

.active {
    border: thick solid green;
}

TypeScript

class MyComponent {
  public allButtons = [false, false, false];

  public btn1 = document.getElementById('btn1');
  public btn2 = document.getElementById('btn2');
  public btn3 = document.getElementById('btn3');
  public myMap: Map<number, HTMLDivElement> = new Map<number, HTMLDivElement>();
  
  constructor() {
  	// hardcoded index mapped to the btn1
    this.myMap.set(0, btn1);
    this.myMap.set(1, btn2);
    this.myMap.set(2, btn3);	
  }

	// the function that is called for the main 3 buttons, pass in an index
  onBtnClick(index: number) {
  	// reset all buttons array
    this.resetAllButtons();
    
    // assign true to the selected index
    this.allButtons[index] = true;
    
    // loop though all buttons
    // - add active to the index that is true
    // - remove active class from the indindex add/remove active class off the button
    this.allButtons.forEach( (isBtnActive, i) => {
      const btn = this.myMap.get(i);
      if(btn) {
        isBtnActive ? btn.classList.add('active') :  btn.classList.remove('active');
      }
    });
    
  }

	// every click will always reset all values to false
  resetAllButtons() {
    this.allButtons = [false, false, false];
  }

}

const comp = new MyComponent();