我的Angular 2应用程序有4个组件。组件是标题,页脚,导航和内容。我在头部组件中有一个按钮,当用户单击头部组件中的按钮时,我想要显示/隐藏导航组件中的内容。我想知道,当我单击标题中的按钮时,如何将Boolean
值从标头组件传递到导航组件。所有组件都有自己的html模板。让我知道什么是将切换值从标题传递给导航组件的方式。组件之间的角度2传递值
感谢
我的Angular 2应用程序有4个组件。组件是标题,页脚,导航和内容。我在头部组件中有一个按钮,当用户单击头部组件中的按钮时,我想要显示/隐藏导航组件中的内容。我想知道,当我单击标题中的按钮时,如何将Boolean
值从标头组件传递到导航组件。所有组件都有自己的html模板。让我知道什么是将切换值从标题传递给导航组件的方式。组件之间的角度2传递值
感谢
您可以采取的sharedservice
和sharedobject
优势,如下图所示。
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:无法读取[showhide.show在edockNavigationComponent @ 3:32]中未定义的属性'show'' – user3739018
你在'export class Navbar {showHide:ImyInterface; ......?}?和'sharedService'中的相同接口。检查我的演示正确。 – micronyks
非常好。我喜欢你使用API,hide(),而不是直接在'showhide()'中修改'show'属性。我想我喜欢使用界面。这似乎比在服务上使用另一个API来获得价值更有效。但是,如果您确实使用API来获取'show'的当前值(例如,'* ngIf =“ss.getShowValue()'),那么您不需要将该布尔值包装在一个对象中。不知道我喜欢哪一种更好......效率还是更好的封装你的想法? –
请添加,显示你的组件,其模板以及它们是如何相关的代码。 –