0

I am working in header part where I need to make open and close function of menu using Angular6.

I could not find any way to fire an function on click event occurred somewhere else but not on some component. So I dicided to make such function with javascript inside angular js. I have following code to do so.

export class HeaderComponent implements OnInit, AfterViewInit {
  menus : any;
  activeLang : string;
  // flag for menu closed or not
  isMenuClosed : any;

  constructor(private router : Router) { 
    this.isMenuClosed = true;
    // assign this object to newInstance so that it can be used inside javascript function
    let newInstance = this;
    // function whenever click event occured
    document.addEventListener("click", function(event){
      // check if event.target.getAttribute('class') is true of not
      // unfortunetly this line shows error event.target.getAttribute property doesnot exists ... 
      // getAttribute is not property its function
      // I also try (event.target as HTMLInputElement).getAttribute()
      if(!!event.target.getAttribute('class'))
      {
        let eventClass = event.target.getAttribute('class');
        // confirm if click has been occured out of menu
        if(!eventClass.includes("ti-close") && 
           !eventClass.includes("nav-toggler") &&
           !eventClass.includes("left-sidebar") && 
           !eventClass.includes("scroll-sidebar") &&
           !eventClass.includes("sidebar-nav") && 
           !eventClass.includes("sidebarnav"))
        {
          newInstance.hideSideBar();
        }
      }
      else
      {
        newInstance.hideSideBar();
      }
    });

    hideSideBar()
    {
      let classString = document.getElementsByTagName('body')[0].getAttribute('class');
      classString =  classString.replace(" show-sidebar","");
      document.getElementsByTagName('body')[0].setAttribute('class',classString);
      this.isMenuClosed = true;
    }
}

This is working perfect if server is not started but got error whenever ng serve -o command has been fired and whole thing stuck in saying error. In terminal it shows error TS2339: Property 'getAttribute' does not exist on type 'EventTarget'

I tried try{}catch(e){}, (event.target as HTMLInputElement).getAttribute('class'),event.target.hasOwnProperty('getAttribute') nothing worked. What's the problem there.

Is there any other way to get the functionality.

Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45
  • 1
    listeing for document:click in a hostListener is the way to go like here https://stackoverflow.com/questions/40107008/detect-click-outside-angular-component – L.A Oct 24 '18 at 13:59
  • thanks @L.A that works fine with little twist – Veshraj Joshi Oct 25 '18 at 07:06

0 Answers0