Home > Net >  Angular get current focused element in angular
Angular get current focused element in angular

Time:12-29

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 >1</div>
<div >2</div>
<div >3</div>

CodePudding user response:

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";
  }

CodePudding user response:

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

selectedIndex:number=-1

If you want not unselected

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

If you want unselected

<div  [class.selected]="selectedIndex==0"
                  (click)="selectedIndex=selectedIndex==0?-1:0">
    1
</div>
<div  [class.selected]="selectedIndex==1"
                  (click)="selectedIndex=selectedIndex==1?-1:1">
    2
</div>
<div  [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
  • Related