小编Den*_*nis的帖子

Angular - 从另一个组件打开/关闭sidenav

我使用角度(最新版本)和角度材料.

有3个组成部分:

  • header.component,其中有一个右侧的控制按钮
  • rigth-sidenav.component,其中是right-sidenav
  • sidenav.component(这是左侧主菜单),这个组件调用header.component,right-sidenav.component和content

我第一次使用Angular,请告诉我,如何从另一个组件打开/关闭sidenav(在我的例子中,按钮在header.component中).

尝试了以下选项(但得到错误:TypeError:this.RightSidenavComponent.rightSidenav未定义):

header.component.html

<button mat-button (click)="toggleRightSidenav()">Toggle side nav</button>
Run Code Online (Sandbox Code Playgroud)

header.component.ts

import { Component } from '@angular/core';
import { RightSidenavComponent } from '../right-sidenav/right-sidenav.component';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent {

    constructor(public RightSidenavComponent:RightSidenavComponent) {   }
    toggleRightSidenav() {
        this.RightSidenavComponent.rightSidenav.toggle();
    }

}
Run Code Online (Sandbox Code Playgroud)

sidenav.component.html

<mat-sidenav-container class="sidenav-container">
    <mat-sidenav #sidenav mode="side" opened="true" class="sidenav"
                 [fixedInViewport]="true"> Sidenav  </mat-sidenav>
    <mat-sidenav-content>
        <app-header></app-header>
        <router-outlet></router-outlet>
        <app-right-sidenav #rSidenav></app-right-sidenav>
    </mat-sidenav-content>
</mat-sidenav-container>
Run Code Online (Sandbox Code Playgroud)

sidenav.component.ts

import { Component, Directive, ViewChild } from '@angular/core';
import { RightSidenavComponent } from '../right-sidenav/right-sidenav.component'; …
Run Code Online (Sandbox Code Playgroud)

typescript angular-material angular

23
推荐指数
4
解决办法
3万
查看次数

标签 统计

angular ×1

angular-material ×1

typescript ×1