【问题标题】:Angular Material: How to toggle sidenav when the trigger is in a different componentAngular Material:当触发器位于不同组件中时如何切换sidenav
【发布时间】:2020-02-25 11:43:38
【问题描述】:

如何从另一个组件切换 sidenav?

当按钮/触发器与 sidenav 在同一个 .html 文件中时,它工作得很好,但如果我生成一个新组件,在我的例子中,我将它们命名为“sidebar-left”和“topbar”,它不会不行。

我所做的是生成组件来分离它们。我将sidenav放在“sidebar-left”组件中,将按钮/触发器放在“topbar”组件中。

sidebar-left.component.html

<mat-sidenav-container>

    <mat-sidenav #sidenav mode="side" [(opened)]="opened" opened>
        <h3>Sidenav</h3>
    </mat-sidenav>

    <mat-sidenav-content>
        <app-dashboard></app-dashboard>
    </mat-sidenav-content>

</mat-sidenav-container>

topbar.component.html

<mat-toolbar>
    <button (click)="sidenav.toggle()" mat-raised-button>Toggle Sidenav</button>
</mat-toolbar>

我希望无论我在应用程序中的哪个位置触发sidenav,都能够触发它。

当我按下切换按钮时,我遇到了这个错误:

TopbarComponent.html:1 ERROR TypeError: Cannot read property 'toggle' of undefined
    at Object.eval [as handleEvent] (TopbarComponent.html:2)
    at handleEvent (core.js:43993)
    at callWithDebugContext (core.js:45632)
    at Object.debugHandleEvent [as handleEvent] (core.js:45247)
    at dispatchEvent (core.js:29804)
    at core.js:42925
    at HTMLButtonElement.<anonymous> (platform-browser.js:2668)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:39680)
    at ZoneDelegate.invokeTask (zone-evergreen.js:390)

Here is my not-working StackBlitz code

【问题讨论】:

    标签: html angular typescript angular-material sidenav


    【解决方案1】:

    组件之间有三种可能的通信方式。您收到的错误是因为您的组件中没有 sidevav 属性,并且未在未定义的成员上声明切换功能。

    您可以通过特定方式在组件之间进行通信。

    使用本机事件驱动的通信。

    父母通过输入(值)传递给孩子,孩子通过输出(事件)传递给父母。

      //this is how to create an event emitter
      @Output() toggle: EventEmitter<any> = new EventEmitter();
    
      constructor() { }
    
      emit() {
          this.toggle.emit(null);
      }
    
    • 在您的 TopbarComponent 中添加上述代码。
    • 在您的 AppComponent 中,您绑定到切换开关

    并在 ts 文件中创建切换功能

    toggle() {
         this.firstSelected = !this.firstSelected;
    }
    

    然后您将第一个选定的值传递给您的组件并相应地隐藏取消隐藏。

    这是官方的方式。检查此解决方案在 stackblitz here

    上的工作

    使用事件服务

    您可以创建一个事件服务,您可以从中引发事件,并且切换主机可以订阅它们并在应用程序范围内切换。检查例如here

    使用库通过存储共享状态

    查看文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-21
      • 2019-05-16
      • 1970-01-01
      • 2019-10-04
      • 2017-02-21
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      相关资源
      最近更新 更多