0

I use material-sidebar for showing the mobile menu. I want to close sidebar when any of item in the menu is clicked.

I send out by the EventEmmiter() function to close the sidebar from child to parent controller.

public onSidenavClose = () => {
        this.sidenavClose.emit();
    };

And here in app.component.html I set like this

<mat-sidenav-container fxFlexFill>
    <mat-sidenav #sidenav (sidenavClose)="sidenav.close()">
      <mat-nav-list>
        <app-nav-item></app-nav-item>
      </mat-nav-list>
    </mat-sidenav>
    <mat-sidenav-content fxFlexFill>Main content</mat-sidenav-content>
  </mat-sidenav-container>

But can not get to close sidebar... some solution?

Here is full working example. You need to resize opened preview in stackblitz to get the mobile nav.

Arter
  • 2,224
  • 3
  • 29
  • 66

1 Answers1

1

You added Event emitter to wrong element, add (sidenavClose)="sidenav.close()" to app-nav-item

<app-nav-item (sidenavClose)="sidenav.close()"></app-nav-item>

EDIT
Your event emitter is on grand child which is <app-nav-list>, @output/Event Emitter is for direct parent, To make this work create a shared service to communicate between any-to-any component, This way you can close sidebar from any component. Stackblitz Example

//Shared Service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class SidebarEventsService {

  closeSidebarEvent = new Subject<string>();
  closeSidebarEvent$ = this.closeSidebarEvent.asObservable();

  constructor() { }

}

nav-list.component.ts

***
import { SidebarEventsService } from '../../sidebar-events.service';

***
constructor(private sidebarEventsService: SidebarEventsService) {}

***
onSidenavClose = () => {
  this.sidebarEventsService.closeSidebarEvent.next();
};

app.component.ts

***
import { SidebarEventsService } from './sidebar-events.service';
@ViewChild("sidenav", { static: false }) sidenav; // For angular 8 only
@ViewChild('sidenav') sidenav; // will be (static: false) by default from angular 9

  constructor(private sidebarEventsService: SidebarEventsService) {
    this.sidebarEventsService.closeSidebarEvent$.subscribe(() => this.sidenav.toggle());
  }
Sameer
  • 4,758
  • 3
  • 20
  • 41
  • Please, sry I put the wrong URL, now I edit...please take a look – Arter Jan 24 '20 at 11:29
  • excelent... when I add `@ViewChild('sidenav') sidenav;` get error `Expected 2 arguments, but got 1.` – Arter Jan 24 '20 at 12:05
  • 1
    In angular 8 a second parameter is required as `@ViewChild('sidenav', {static: false})` [Read more here](https://stackoverflow.com/a/56359612/11719787). Happy coding :) – Sameer Jan 24 '20 at 12:09
  • thank you thank you.... pls edit in ur answer to `@ViewChild("sidenav", { static: false }) sidenav;` – Arter Jan 24 '20 at 12:12