简体   繁体   中英

Angular 2 passing value between components

I have 4 components on my Angular 2 app. 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. All the components have their own html templates. 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.

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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