2017-01-30 63 views
0

我有我的header component有一個功能,可以在點擊時切換一個類,這完全適用於頭部組件,但我想將該行爲傳遞給我的nav component,它根據這個事件。如何通過組件傳遞變量Angular 2

我的問題:

我如何可以訪問內部nav component這些變量?

期望的行爲:

我要的是能夠添加CSS clases當我點擊toggleMenu

代碼:

標題組件:

import { Component, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-header', 
    templateUrl: './header.component.html', 
    styleUrls: ['./header.component.scss'] 
}) 

export class HeaderComponent implements OnInit { 

    private showOpened : boolean; 

    constructor() { 

    } 

    ngOnInit() { 
    this.showOpened = false; 
    } 


    toggleMenu() { 
    this.showOpened = !this.showOpened;; 
    } 
} 

標題HTML:

<div class="header-container"> 
    <header class="wrapper clearfix"> 
    <h1 class="logo">---</h1> 
    <input type="checkbox" class="checkbox-menu" id="menu-toogle"> 
    <label for="menu-toogle" class="menu-toogle" (click)="toggleMenu()"></label> 
    <div class="bar" [class.animate]="showOpened"></div> 
    <span class="icon-search"></span> 
    </header> 
</div> 

導航組件

import { Component, Input, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-nav', 
    templateUrl: './nav.component.html', 
    styleUrls: ['./nav.component.scss'] 
}) 

export class NavComponent implements OnInit { 
    constructor() { } 

    ngOnInit() { 
    } 

} 

導航HTML

<nav [class.open-menu]="showOpened"></nav> 
+0

看看@Input:http://learnangular2.com/inputs/ – Seiyria

+0

此外,請注意您使用的是正確的選擇器。我發現你使用'nav'和'header'而不是'app-nav'和'app-header' - 這不會像你期望的那樣工作。 – Seiyria

回答

0

嘗試此代碼: 部首HTML

<div class="header-container"> 
    <header class="wrapper clearfix"> 
    <h1 class="logo">---</h1> 
    <input type="checkbox" class="checkbox-menu" id="menu-toogle"> 
    <label for="menu-toogle" class="menu-toogle" (click)="toggleMenu()"></label> 
    <div class="bar" [class.animate]="showOpened"></div> 
    <span class="icon-search"></span> 
    </header> 
    <app-nav [showOpened]="showOpened"></app-nav> <!-- put this code where you want to place your nav --> 
</div> 

導航組件

import { Component, Input, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-nav', 
    templateUrl: './nav.component.html', 
    styleUrls: ['./nav.component.scss'] 
}) 

export class NavComponent implements OnInit { 

    @Input() showOpened: boolean; 
    constructor() { } 

    ngOnInit() { 
    } 

} 

導航HTML

<nav [class.open-menu]="showOpened"></nav> <!-- Now you can access showOpened value from parent header --> 

您可以找到有關角文檔組件交互的更多信息: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child

+0

非常感謝你,閱讀和閱讀後,我終於明白這是如何工作的。順便說一句,只是最後一個問題,如果他們是兄弟姐妹,我想我應該創建一個服務? –

+0

我可能是錯的,但我認爲兄弟姐妹組件現在無法互動。如果您創建服務並在AppModule中提供它,則這兩個組件將使用您的服務的不同實例,因此您無法檢索相同的數據。要使它們使用同一服務實例,您必須僅在父組件中提供它,以便子組件可自動訪問同一實例。 – mickdev