6

I want to access the child component's element (#sidenav) in parent component (toggleSidebar()). I tried to apply this solution without success: angular 2 / typescript: get hold of an element in the template

My Child Component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-sidebar',
  template: `
  <md-sidenav #sidenav mode="side" class="app-sidenav">
  Sidenav
  </md-sidenav>
  `,
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

My Parent Component:

import { SidebarComponent } from './sidebar/sidebar.component';
import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <app-sidebar></app-sidebar>
  <app-toolbar (toggleSidebar)="toggleSidebar()"></app-toolbar>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @ViewChild('sidenav') sidebar: SidebarComponent;

  constructor() { }

  toggleSidebar() {
    this.sidebar.toggle();
  }
}
Community
  • 1
  • 1
Runtime Terror
  • 6,242
  • 11
  • 50
  • 90

1 Answers1

11

Update for Angular 8:

@ViewChild(SidebarComponent, {static: false}) sidebar: SidebarComponent;

For more info check: https://angular.io/guide/static-query-migration


You should get the child component from parent with

@ViewChild(SidebarComponent) sidebar: SidebarComponent;

so remove the sidenav

and add it to the child component to get hold of that element.

@ViewChild('sidenav') sidenav;

finally call your child components sidenav field from parent to do whatever you want.

this.sidebar.sidenav// <-- selects child components element

parent:

import { SidebarComponent } from './sidebar/sidebar.component';
import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <app-sidebar></app-sidebar>
  <app-toolbar (toggleSidebar)="toggleSidebar()"></app-toolbar>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @ViewChild(SidebarComponent) sidebar: SidebarComponent;

  constructor() { }

  toggleSidebar() {
    this.sidebar.sidenav.toggle();
  }
}

child:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-sidebar',
  template: `
  <md-sidenav #sidenav mode="side" class="app-sidenav">
  Sidenav
  </md-sidenav>
  `,
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
  @ViewChild('sidenav') sidenav;
  constructor() { }

  ngOnInit() {
  }

}
eko
  • 39,722
  • 10
  • 72
  • 98