2

i have a modal for show notification in angular 9 .

i have a button for show or hide modal and it's worked find , but i need when click on the other place of page ( not show/hide button ) If the modal is on show, hide it .

this is Demo .

html :

    <div class="header">
 <button (click)="toggleFunction()">show</button>
<div class="showButton" id="showNotification">
  <span>this is test</span>
</div>
</div>

ts :

   export class TopeheaderComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
    toggleFunction() {
        let element = document.getElementById('showNotification');
        if (element.style.display === '' || element.style.display === 'none') {
            element.style.display = 'block';
        } else if (element.style.display === 'block') {
            element.style.display = 'none';
        }
    }
}

how can i solve this problem ?

mr coder
  • 199
  • 2
  • 14
  • 1
    Please check this answer: https://stackoverflow.com/questions/35712379/how-can-i-close-a-dropdown-on-click-outside – vcaraccio Apr 07 '20 at 06:18

2 Answers2

2

you can use HostListener to detect click outside the target element

component

  isHide: boolean = true;

  toggleFunction(e: MouseEvent) {
    e.stopPropagation();
    this.isHide = !this.isHide; // toggle the notification 
  }

  @HostListener("document:click") hideOnClick() {
    this.isHide = true;
  }

template

<div class="header">
    <button (click)="toggleFunction($event)">show</button>
    <div class="showButton" [ngClass]="{'d-none':isHide}">
        <span>this is test</span>
    </div>
</div>

I just update the logic of update the the element base of toggle class with ngClass directive is more readable an easier. stopPropagation stop the event from bubbling so upper event listener will not capture this event.

demo

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
1

You can use HostListener and ViewChild. Please add this selector on your html

<button #showButton (click)="toggleFunction()">show</button>

and add your ts file

@ViewChild('showButton') showButton: ElementRef;
@HostListener('document:click', ['$event'])
  clickout(event) {
    let element = document.getElementById('showNotification');
    if (element.style.display === 'block') {
      if (!document.getElementById('showNotification').contains(event.target) &&
      !this.showButton.nativeElement.contains(event.target) ) {
        element.style.display = 'none';
      }
    }
}

WORKING DEMO

ahmeticat
  • 1,899
  • 1
  • 13
  • 28
  • This does work, but I would also discourage Angular newcomers from manually manipulating the DOM like this. There are more "Angular" ways of showing and hiding elements. – Kurt Hamilton Apr 07 '20 at 06:29