组件之间的角度2传递值

时间:2016-04-01 06:40:19

标签: angular

我的Angular 2应用程序上有4个组件。组件是页眉,页脚,导航和内容。我在标题组件中有一个按钮,当用户从标题组件中单击按钮时,我想显示/隐藏导航组件中的内容。我想知道当我从标题中单击按钮时如何将Boolean值从标题组件传递到导航组件。所有组件都有自己的html模板。让我知道将切换值从标题传递到导航组件的方法是什么。

由于

1 个答案:

答案 0 :(得分:2)

您可以使用sharedservicesharedobject,如下所示。

<强> working demo

<强> sharedService.ts

export interface ImyInterface {
   show:boolean;
}

@Injectable()
export class sharedService {
  showhide:ImyInterface={show:true};

  hide(){
        this.showhide.show=!this.showhide.show;
  }
} 

header.ts(content.ts)

import {Component,Injectable} from 'angular2/core';
import {sharedService} from 'src/sharedService';

@Component({
  selector: 'thecontent',
    template: `
    <div>Header Component <button (click)=showhide()>show/hide</button></div>
    `
})
export class TheContent {
  constructor(private ss: sharedService) {
    console.log("content started");
  }
  showhide() {
    this.ss.hide();
  }
}

navigation.ts(nav.ts)

import {Component,bind} from 'angular2/core';
import {sharedService} from 'src/sharedService';

@Component({
  selector: 'navbar',
  template: `
  <style>
    .bk{
          background-color:black;
          color:white;
    }
  </style>
  <div>Navigation Component </div>
  <div [class.bk]="true" *ngIf="showHide.show"> Showing </div>
  <hr>
  <hr>
  `
})
export class Navbar {
  showHide:ImyInterface;
  constructor(ss: sharedService) {
    this.showHide=ss.showhide;
  }
}
相关问题