Search code examples
htmlangulardirective

how to make custom directive manipulate another elements in angular


my problem is i have a div that's visible and another div that's hidden what i want to do is to make the second div visible whenever i hover over the first div so i made a custom directive to help me do that but the problem is the custom directive only take effect on the element that's assigned to as an attribute here's my html code

<div appCustomlang>Visible</div>
<div>Invisible</div>

and here's my cutsom directive code

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appCustomlang]',
})
export class CustomlangDirective {
  @HostListener('mouseover') OnMouseOver() {
    this.elm.nativeElement.style.display = 'none';
  }
  @HostListener('mouseout') OnMouseOut() {
    this.elm.nativeElement.style.display = 'block';
  }
  constructor(private elm: ElementRef) {}
}

so this code only works on the visible div so how can i make work and manipulate the invisible div whenever i hover over the visible div as i explained above?


Solution

  • You don't need a directive here - just straight CSS.

    First set your hidden div to be display: none.. .and then add a :hover pseudo-selector to the first div and a direct-sibling combinator (+) so that the hovering on the first div - applies the display: block styling to the second one. Note that I added padding and borders to more easily show the affected divs.

    This is assuming it is directly after the first div... if its not - use the general-sibling combinator (~) and you will get the same effect. No Angular directives were harmed in the making of this snippet :)

    div {
      padding: 8px;
      border: solid 1px red
    }
    
    .hidden-div {
     display: none;
     border-color: blue;
    }
    
    .visible-div:hover + .hidden-div {
     display: block
    }
    <div class="visible-div">I am visible all the time</div>
    <div class="hidden-div">I am visible when you hover on my friend :)</div>