我的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()'),那麼您不需要將該布爾值包裝在一個對象中。不知道我喜歡哪一種更好......效率還是更好的封裝你的想法? –
請添加,顯示你的組件,其模板以及它們是如何相關的代碼。 –