2

enter image description hereI have a website I am trying to do something like this, when I click on 1, I want the background of this element to change to white and when I click on the second one the background of the first one will disappear and pass to the next one...I have been trying to do this for a long time help me I don't know how to do it

<div class="oval">1</div>
<div class="oval">2</div>
<div class="oval">3</div>
1
  • With css use the :focus state Commented Dec 28, 2022 at 14:52

2 Answers 2

1

When we need make "something" exclusive we use one unique variable

selectedIndex:number=-1

If you want not unselected

<div class="oval" [class.selected]="selectedIndex==0"
                  (click)="selectedIndex=0">
    1
</div>
<div class="oval" [class.selected]="selectedIndex==1"
                  (click)="selectedIndex=1">
    2
</div>
<div class="oval" [class.selected]="selectedIndex==2"
                  (click)="selectedIndex=2">
    3
</div>

If you want unselected

<div class="oval" [class.selected]="selectedIndex==0"
                  (click)="selectedIndex=selectedIndex==0?-1:0">
    1
</div>
<div class="oval" [class.selected]="selectedIndex==1"
                  (click)="selectedIndex=selectedIndex==1?-1:1">
    2
</div>
<div class="oval" [class.selected]="selectedIndex==2"
                  (click)="selectedIndex=selectedIndex==2?-1:2">
    3
</div>

NOTE: I use [class.selected], so we use a .css

.selected{
   background:red;
}

You can use style.background or style.background-color using (condition)?value:null, e.g., for the first div

[style.background]="selectedIndex==0?'red':null
Sign up to request clarification or add additional context in comments.

Comments

0

Like @Kwright02's comment you can do it with css:

.myclass:focus {
  background-color: green;
}

But important: The element must be focusable. So a div isn't, a button is as example.

Second way (add a click handler and change the background directly):

// HTML
<div (click)="onClick($event)">test</div>

// Code
onClick(event: any) {
    event.target.style["background-color"] = "green";
  }

Note: This is not the way to go in Angular. Here use property binding and bind a style to a condition as example.

Instead of add a click listener to each control you can use Angular's HostListener like this:

 @HostListener("document:click", ["$event"])
  onAllClick(event: any) {
    event.target.style["background-color"] = "green";
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.