Home > OS >  How to highlight an element when I click on a different element in angular
How to highlight an element when I click on a different element in angular

Time:11-04

Picture of what I want to accomplish

So I have this original box lets say box #1 (shown on left). Box #1 has a button on it that when it is clicked, it opens box #2 (shown on right). Box #2 contains a button on it that when that is clicked, I want box #1 to highlight to show that box #2 came from box #1. Any ideas on how to do this?

I was trying stuff with ng-click but can't figure out what exactly needs to be in it

CodePudding user response:

There are many ways to achieve this with varying levels of complexity depending on what you need from the system and the components in place.

To start, here's a very basic solution that achieves what you are after, all achieved through an object which holds the state of the system. Added an *ngFor to demonstrate how you could easily achieve multiple boxes (assuming this would be beneficial). Stackblitz

.html

<div >
  <div
    *ngFor="let box of boxes"
    >
    <div
      
      [class.is-flashing]="box.flashBoxOne">
      <button (click)="box.showBoxTwo = !box.showBoxTwo">{{ !box.showBoxTwo ? 'Show' : 'Hide' }}</button>
    </div>
    
    <div
      *ngIf="box.showBoxTwo"
      >
      <button (click)="box.flashBoxOne = !box.flashBoxOne">{{ !box.flashBoxOne ? 'Flash' : 'Stop' }}</button>
    </div>
  </div>

  <button (click)="addBoxGroup()">Add Box Group</button>
</div>

.ts

boxes = [
  {
    showBoxTwo: false,
    flashBoxOne: false,
  },
]

addBoxGroup() {
  this.boxes.push({
    showBoxTwo: false,
    flashBoxOne: false,
  })
}

.scss


.box-group-container {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .box-group {
    display: flex;
    flex-direction: row;
    gap: 8px;
  
    .box {
      height: 100px;
      width: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &.is-flashing {
        animation: flashing 0.5s infinite;
      }
    }
    
    .box-one {
      background-color: blue;
    }
    
    .box-two {
      background-color: red;
    }
  }
}

@keyframes flashing {
  0% { opacity: 1.0; }
  50% { opacity: 0.0; }
  100% { opacity: 1.0; }
}
  • Related