【问题标题】:Angular 2 passing value between componentsAngular 2在组件之间传递值
【发布时间】:2016-07-20 20:46:17
【问题描述】:

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

谢谢

【问题讨论】:

  • 请添加代码以显示您的组件、它们的模板以及它们之间的关系。

标签: angular


【解决方案1】:

您可以利用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;
  }
}

【讨论】:

  • 感谢您的解决方案。我尝试了您提供的代码。我收到此错误EXCEPTION: TypeError: Cannot read property 'show' of undefined in [showHide.show in edockNavigationComponent@3:32]
  • 您在export class Navbar{ showHide:ImyInterface; ... ... ...} 中写过这行代码吗?和sharedService 中的相同界面。正确检查我的演示。
  • 非常好。我喜欢您使用 API hide(),而不是直接在 showhide() 中修改 show 属性。我想我喜欢使用界面。这似乎比在服务上使用另一个 API 来获取价值更有效。但是,如果您确实使用 API 来获取 show 的当前值(例如,*ngIf="ss.getShowValue()),那么您不需要将布尔值包装在对象中。我不确定我更喜欢哪个......效率或更多封装。你的想法?
  • @MarkRajcok 很高兴你喜欢它。但是你能不能请叉子告诉我你想要什么? (因为可以有不同的方式)
  • 这不是“我想要的”,而是更像……你觉得这种方法怎么样?:plnkr.co/edit/n7MxhJoLDCLZbl4mOxjX?p=preview我在NgIf表达式中调用服务上的一个函数,而不是依赖共享引用类型。
猜你喜欢
  • 2017-08-12
  • 2016-04-29
  • 1970-01-01
  • 2021-04-13
  • 2018-02-22
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 2016-03-24
相关资源
最近更新 更多