您应该从父级获取子组件
@ViewChild(SidebarComponent, {static: false}) sidebar: SidebarComponent;
所以删除 sidenav
并将其添加到子组件以获取该元素.
@ViewChild(SidebarComponent) sidebar: SidebarComponent;
最后sidenav
从父母调用您的子组件字段来做您想做的任何事情.
this.sidebar.sidenav// <-- selects child components element
父母:
@ViewChild('sidenav') sidenav;
儿童:
import { SidebarComponent } from './sidebar/sidebar.component'; import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'app-root', template: ``, styleUrls: ['./app.component.css'] }) export class AppComponent { @ViewChild(SidebarComponent) sidebar: SidebarComponent; constructor() { } toggleSidebar() { this.sidebar.sidenav.toggle(); } }