我想检查一下我的
<md-sidenav>
即将关闭。
有没有办法使用我的 sidenav 对象的 EventEmitter onClose 来检查?
你能举个例子吗?
这可以通过两种不同的方式实现 - 通过模板,以及在组件代码本身内。
假设 HTML 模板如下所示:
<md-sidenav-container>
<md-sidenav #mySidenav (close)="onClose()" mode="side">
This is sidenav content
</md-sidenav>
<button md-raised-button (click)="mySidenav.toggle()">Toggle Sidenav</button>
</md-sidenav-container>
在你的组件中你可以有这样的东西:
import { AfterViewInit, Component, OnDestroy, ViewChild } from '@angular/core';
import { MdSidenav } from '@angular/material'
import { Subscription } from 'rxjs'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('mySidenav')
sidenav: MdSidenav;
subscription: Subscription;
ngAfterViewInit(): void {
this.subscription = this.sidenav.onClose.subscribe(() =>
console.log("Closed event from observable"));
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
onClose(): void {
console.log("Closed event from template");
}
}
技术 1 是使用事件绑定。这是(close)="onClose()"
模板的部分。每当 sidenav 触发 close 事件时,引号中指定的代码(即onClose()
)运行。在这种情况下,该方法onClose()
(在组件代码中定义)被调用,并将一些文本打印到控制台。您可以在以下位置找到有关此技术的更多信息角度文档的事件绑定部分。 https://angular.io/docs/ts/latest/guide/template-syntax.html#!#event-binding
技术 2 是在组件代码本身中订阅事件。在这种技术中,我们将 sidenav 导出为变量mySidenav
。这是#mySidenav
模板的部分。在组件代码中,我们可以使用以下命令获取对 sidenav 的引用@ViewChild('mySidenav')
注解。当我们的组件初始化时,我们可以访问 sidenav,因此每当关闭事件被触发时就运行一些代码。在这种情况下,我们使用subscribe()
的方法Observable
界面。当组件被销毁时,取消订阅很重要,以防止内存泄漏,因此unsubscribe()
打电话进来ngOnDestroy()
。您可以在中找到有关可观察量的更多信息rxjs 文档的 Observables 部分 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/subscribe.md.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)