组件之间的Angular 2传递值 [英] Angular 2 passing value between components

查看:58
本文介绍了组件之间的Angular 2传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

谢谢

推荐答案

您可以利用sharedservicesharedobject,如下所示.

You can take advantage of sharedservice and sharedobject as shown below.

工作演示

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

这篇关于组件之间的Angular 2传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆