angular - 从类中调用组件的方法

标签 angular angular-material

我有 Material 2 sidenav我的应用程序中的组件。如何从我的类中访问组件方法?就我而言,我想调用 open()方法。在模板中与 <button md-button (click)="sidenav.open()"> 配合使用完全没问题,但是如果我通过 this.el.nativeElement.open(); 在类中使用该方法,它抛出:

ERROR TypeError: Cannot read property 'open' of undefined

我的组件:

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-sidebar-content',
  template: `
    <md-sidenav-container class="example-container">

      <md-sidenav #sidenav class="example-sidenav">
        Jolly good!
      </md-sidenav>

      <div class="example-sidenav-content">
        <button md-button (click)="sidenav.open()">
          Open sidenav
        </button>
      </div>

    </md-sidenav-container>
  `,
  styleUrls: ['./sidebar-content.component.css']
})
export class SidebarContentComponent implements OnInit {

  @ViewChild('sidenav') el: ElementRef;

  constructor() { }

  ngOnInit() {

  }

  openSideNav() {
    // this.el.nativeElement.open();
    // ERROR TypeError: Cannot read property 'open' of undefined
  }

}

最佳答案

我认为您滥用了ViewChild。 看一下ViewChild的官方文档:https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

ViewChild 采用您要跟踪的组件的类类型。在你的情况下,我想它是 MdSidenav 。 您应该按如下方式更改代码,以便能够访问您在模板中注入(inject)的第一个 sidenav 组件:

export class SidebarContentComponent implements OnInit {

  @ViewChild(MdSidenav) sidenav: MdSidenav;

  constructor() { }

  ngOnInit() {

  }

  openSideNav() {
    this.sidenav.open();
  }

}

关于angular - 从类中调用组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44184935/

相关文章:

javascript - TS2322 : Type 'Promise<Hero | undefined>' is not assignable to type 'Promise<Hero>'

angular - 单击 Angular 6 中的按钮时调用不同的函数

angular - 在对话框中重用组件的 Angular 、 Material 的最佳实践?

html - 创建可重用 Angular UI 组件的最佳方法

android - 应用程序进入后台时未触发 ionic 事件(平台暂停)

angular - 在 ionic 搜索栏上输入验证?

angular - Material Angular - 编译错误 - 类 'MatStepper' 错误地扩展了基类 'CdkStepper'

angularjs - 在 md-radio-button 中保存 bool 值?

angular - Angular 2的转译过程

angular - 如何使用 Jasmine 测试 MatSort