Home > Software design >  How to add querySelector in window.addEventListener in angular?
How to add querySelector in window.addEventListener in angular?

Time:07-13

i would like to add a close dropdown button in angular when user click outside? I use window.addEventListener to detect user click outside or not. However, it seem to be use document.querySelector cannot detect a element. How to deal with it ?

Here is what I've tried :

export class AppComponent {
  constructor() {}

  ngAfterViewInit() {
    let checkbox = document.querySelector('#delete-drop-down');

    window.addEventListener('click', () => {
      this.el.nativeElement.checkbox.natveElement.checked = false;
    });

    window.addEventListener('click', (event) => {
      event.stopPropagation();
    });
  }
}

here is stackblitz

CodePudding user response:

Well, if you are using Angular you should get used to not using document.querySelector or window.addEventListener. Angular is here to encapsulate those things for you.

A proper implementation should include a @HotsListener for listening document or window click events. And some @ViewChild for accessing elements in the template. And ngModel to bind the checked value for the check box.

Here is what your AppComponent should look like :

export class AppComponent {
  @ViewChild('check', { static: false })
  checkInput: ElementRef<HTMLInputElement>;

  @ViewChild('btn', { static: false })
  btnInput: ElementRef<HTMLButtonElement>;

  isDropDownOpen = false;

  @HostListener('document:click', ['$event'])
  windoClick($event: MouseEvent) {
    if (
      $event.target === this.checkInput.nativeElement ||
      $event.target === this.btnInput.nativeElement
    ) {
      console.log('skipping');
      return;
    }
    this.isDropDownOpen = false;
  }
}

And your component template should look like :

  <button  #btn>Delete</button>

  <input
    type="checkbox"
    name=""
    [(ngModel)]="isDropDownOpen"
    id="delete-drop-down"
    #check
  />
  <label  for="delete-drop-down">
    <span ></span>
  </label>

Stackblitz

CodePudding user response:

Just use

  @HostListener('window:click', ['$event'])
  stopPropagation(event){
    console.log(document.querySelector('#delete-drop-down'))
  }
  • Related