我有 2 个组件,主 app.component 和一个 header.component 现在我想在标题中放置一个按钮,用于切换一个类在主 app.component 中处于事件状态我让按钮在 app.component 中工作但我想将按钮移动到页眉组件但具有相同的功能
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
在您的 header 组件中,您可以向该类添加一个 EventEmitter 属性
@Output() sidebarToggled = new EventEmitter<boolean>();
然后绑定(bind)到您的主要应用程序组件中的事件
<app-header (sidebarToggled)="onSidebarToggled($event)"></app-header>
在 app.component.ts 中
onSidebarToggled(toggled: boolean) {
...
}
如果这对您的情况不起作用,您还可以使用注入(inject)到两个组件中的通用服务
关于javascript - 我如何将点击事件定位到 Angular 2 中的另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46821176/