简体   繁体   English

组件之间的角度2传递值

[英]Angular 2 passing value between components

I have 4 components on my Angular 2 app. 我的Angular 2应用程序上有4个组件。 Components are Header, Footer, Navigation and Content. 组件是页眉,页脚,导航和内容。 I have a button in the header component and I want to show/hide the content in the navigation component when user click on the button from the header component. 我在标题组件中有一个按钮,当用户从标题组件中单击按钮时,我想显示/隐藏导航组件中的内容。 I want to know that when I click the button from the header how to pass the Boolean value from header component to the navigation component. 我想知道,当我单击标题中的按钮时,如何将Boolean值从标题组件传递到导航组件。 All the components have their own html templates. 所有组件都有自己的html模板。 Let me know what is the way to pass the toggle value from header to navigation component. 让我知道将切换值从标题传递到导航组件的方法是什么。

Thanks 谢谢

You can take advantage of sharedservice and sharedobject as shown below. 您可以利用sharedservicesharedobject ,如下所示。

working demo 工作演示

sharedService.ts 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) 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) 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;
  }
}

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

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