Getting a reference to an element of a child component in a parent component

I want to access an element of a child component ( #sidenav ) in the parent component ( toggleSidebar() ). I tried to apply this solution without success: angular 2 / typescript: get element in 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(); } } 
+6
source share
1 answer

Update for Angular 8:

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

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


You should get a child component from parent with

 @ViewChild(SidebarComponent) sidebar: SidebarComponent; 

so remove sidenav

and add it to the child component to get this element.

 @ViewChild('sidenav') sidenav; 

finally, call the sidenav child component sidenav 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() { } } 
+9
source

Source: https://habr.com/ru/post/1262598/


All Articles