我的header component
具有在点击时切换类的功能,这在头部组件中完美地工作,但我想将该行为传递给我的nav component
,根据它添加类这个事件。
我的问题:
如何在nav component
?
所需行为
我想要的是能够在点击toggleMenu
时添加css clases代码:
标题组件:
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 :(得分:2)
试试这段代码: 标题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 -->
您可以在angular doc中找到有关组件交互的更多信息: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child
答案 1 :(得分:1)
最好的方法是通过服务实现组件通信,因为侧面菜单和标题或工作区域是独立的或兄弟组件
访问以下angular 2网站并实施该服务 https://angular.io/docs/ts/latest/cookbook/component-communication.html