Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a reference to the child component's element in the parent component

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();
  }
}
like image 726
Runtime Terror Avatar asked Jan 10 '17 18:01

Runtime Terror


Video Answer


1 Answers

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() {
  }

}
like image 109
eko Avatar answered Sep 29 '22 01:09

eko