繁体   English   中英

我如何将点击事件定位到 Angular 2 中的另一个组件

[英]How can i target a click event to another component in Angular 2

我有 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 中放置相同的按钮,但它似乎没有工作

任何帮助,将不胜感激! 谢谢

您可以使用事件在组件之间进行通信, 请参阅 angular 文档

在您的头组件中,您可以向类添加一个 EventEmitter 属性

@Output() sidebarToggled = new EventEmitter<boolean>();

然后绑定到主应用程序组件中的事件

<app-header (sidebarToggled)="onSidebarToggled($event)"></app-header>

并在 app.component.ts

onSidebarToggled(toggled: boolean) {
    ...
}

如果这对您的情况不起作用,您还可以使用注入到两个组件中的公共服务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM