Home > Back-end >  How can I code this (click) function on angular?
How can I code this (click) function on angular?

Time:08-10

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(){
  
  }

CodePudding user response:

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;
}
  • Related