我有 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/