我如何将一个点击事件定位到Angular 2中的另一个组件
问题描述:
我有两个组件主app.component和一个header.component现在我想在标题中放置一个按钮,该按钮将一个类切换为在主app.component Ive得到的按钮,在工作app.component但我想按钮移动到头部组件,但具有相同的功能我如何将一个点击事件定位到Angular 2中的另一个组件
HTML
<div>
<button type="button" id="sidebarCollapse" class="btn btn-primary"
(click)="togglesideBar(); toggleSign();">
<i class="glyphicon glyphicon-{{sign}}"></i>
</button>
</div>
<!--Chat Side Bar-->
<div id="chatsidebar" [ngClass]="{'active': isSideBarActive}">
<app-chatsidebar></app-chatsidebar>
</div>
</div>
APP.COMPONENT.TS
sign = 'chevron-right';
toggleSign() {
if (this.sign === 'chevron-right') {
this.sign = 'chevron-left';
} else {
this.sign = 'chevron-right';
}
}
togglesideBar() {
this.isSideBarActive = !this.isSideBarActive;
}
我试着在header.component.ts中放入相同的函数,并将相同的按钮放在header.component.html中,但它似乎并不工作
任何帮助,将不胜感激! 感谢
答
您可以使用事件see the angular docs
组件之间的通信。在你的头组件,您可以在EventEmitter属性添加到类
@Output() sidebarToggled = new EventEmitter<boolean>();
然后绑定到事件在你的主应用程序组件
<app-header (sidebarToggled)="onSidebarToggled($event)"></app-header>
and the app.component.ts
onSidebarToggled(toggled: boolean) {
...
}
如果没有你的情况下工作,你也可以使用,被注入到这两个组件下面
德文的答案是这样做的一种方式共同服务。根据你的应用程序的复杂程度,虽然你可能想看看ngRx这是一个更复杂的解决方案,但也解决了其他许多问题。 https://www.youtube.com/watch?v=cyaAhXHhxgk –