如何将一个按钮单击功能调用到另一个组件?

时间:2017-03-16 09:50:29

标签: angular typescript

以下是我在dashboard.html中的三个组件

<top-nav></top-nav>
<sidebar-cmp></sidebar-cmp>
<section class="main-container" [ngClass]="{sidebarPushRight: isActive}">   
  <router-outlet></router-outlet>
</section>

此处sidebar.html

<button type="button" class="btn btn-primary menu-icon" (click)="toggleMenu()"><i class="fa fa-bars"></i></button>
 <nav class="sidebar" [ngClass]="{sidebarPushRight: isActive, sidebarHide: isHide}">
 <ul class="list-group">
    <a routerLink="/dashboard/home" [routerLinkActive]="['router-link-active']" class="list-group-item">
        <i class="fa fa-fw fa-home"></i> Home
    </a>
  </ul>
<nav>

这是sidebar.component.ts

import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Auth } from '../../login/auth.service';
import { Menu } from '../../webapi/model/models';
import { User } from '../../webapi/model/models';
import * as _ from 'lodash';

@Component({
moduleId: module.id,
selector: 'sidebar-cmp',
templateUrl: 'sidebar.html',
styleUrls: ['sidebar.css']
})

export class SidebarComponent implements OnInit {
 isHide = false;
 public toggleMenu(){
    this.isHide = !this.isHide;
  }
}

我在sidebar.html中有一个按钮,如果我点击sidebar.html上的menu-icon按钮,我想在dashboard.html中向主容器类添加一个ngClass。请任何人帮忙。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用EventEmitter和双向数据绑定isActive属性

<sidebar-cmp [(isHide)]="isActive"></sidebar-cmp>


export class SidebarComponent implements OnInit {
 @Input() isHide: boolean = false;
 @Output() isHideChange: EventEmitter = new EventEmitter();
 public toggleMenu(){
    this.isHide = !this.isHide;
    this.isHideChange.emit(this.isHide);
  }
 }

答案 1 :(得分:0)

使用@Output装饰器:

export class SidebarComponent implements OnInit {
 isHide = false;
  @Output() onActivate = new EventEmitter(); 
 public toggleMenu(){
    this.isHide = !this.isHide;
    onActivate.emit(!this.isHide);
  }
 }


export class DashBoardComponent implements OnInit {
 isActive= false;
  @Output() onActivate = new EventEmitter(); 
 public onActivate(isActive){
    this.isActive= isActive;
  }
 }

HTML:

 <sidebar-cmp (onActivate)="onActivate($event)"></sidebar-cmp>