1

So I want to add a (click) function on three buttons. When I first enter the page the first button should be the one which is selected while the other two are unselected. If I click on the button which is already selected it stays selected, but when I click in one of the unselected buttons the one which I click becomes selected and the previously selected one becomes unselected. Here is the code I wrote until now:

HTML

<div role="button" (click)="[button1 = !button1, buttons()]">
    <p>button</p>
    <button *ngIf="button1"> selected  
    </button>
    <button *ngIf="!button1"> unselected      
    </button>
</div>

<div role="button" (click)="[button2 = !button2, buttons()]">
    <p>button</p>
    <button *ngIf="button2"> selected   
    </button>
    <button *ngIf="!button2"> unselected      
    </button>
</div>

<div role="button" (click)="[button3 = !button3, buttons()]">
    <p>button</p>
    <button *ngIf="button3"> selected   
    </button>
    <button *ngIf="!button3"> unselected     
    </button>
</div>

TS

  button1 = true
  button2 = false
  button3 = false

  constructor() { }

  ngOnInit(): void {
  }

  buttons(){
  
  }

1 Answer 1

1

HTML

<button [class.selected]="button === 'button1'" (click)="onClickButton('button1')">button 1</button>
<button [class.selected]="button === 'button2'" (click)="onClickButton('button2')">button 2</button>
<button [class.selected]="button === 'button3'" (click)="onClickButton('button3')">button 3</button>

TS

button = 'button1'

onClickButton(button: string) {
  this.button = button
}

CSS

button {
  background-color: black;
  color: white;
}


button.selected {
  background-color: white;
  color: black;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.