我试图使用单击事件切换类的打开/关闭,我遇到的问题是我的单击事件在父组件中,而类在子组件中。我能够使用@Input()装饰器初始化类的子类,但我无法切换类之后
import { Component, AfterViewInit, Input, OnInit } from '@angular/core';
import { SidebarComponent } from './components/sidebar/sidebar.component';
@Component({
moduleId: module.id,
selector: 'body',
host: {
'[class.navMdClass]' : 'navMdClass',
'[class]' : 'classNames'
},
templateUrl:'app.component.html' ,
directives:[SidebarComponent],
})
export class AppComponent implements OnInit {
private isClassVisible:boolean;
constructor () {
}
ngOnInit() {
this.isClassVisible=true;
}
toggleClass() {
this.isClassVisible = !this.isClassVisible;
}
}
//Child component
import { Component, Input, EventEmitter, OnInit,SimpleChange } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'sidebar',
templateUrl:'sidebar.component.html'
})
export class SidebarComponent implements OnInit{
@Input() isClassVisible:boolean;
ngOnInit() { }
}
//Parent click event triggers toggleClass
<div class="nav toggle">
<a (click)="toggleClass();" href="#" id="menu_toggle"><i class="fa fa-bars"></i></a>
</div>
//Child div where target class is
<div class="left_col" [class.scroll-view]="[isClassVisible]" >
你需要去掉[class]中的大括号。scroll-view]="[isClassVisible]" to
[class.scroll-view]="isClassVisible"
我找到了这个问题的解决方案,这个解决方案包括将类名作为属性传递给子组件。如果你有多个类要传递到不同的位置,你可以传递一个数组属性并在适当的区域输出。
//parent component
import { Component, AfterViewInit, Input, OnInit } from '@angular/core';
import { SidebarComponent } from './components/sidebar/sidebar.component';
@Component({
moduleId: module.id,
selector: 'body',
host: {
'[class.navMdClass]' : 'navMdClass',
'[class]' : 'classNames[0]'
},
templateUrl:'app.component.html' ,
directives:[SidebarComponent]
})
export class AppComponent{
navMdClass:boolean;
classNames:Array<any>;
constructor () {
this.navMdClass=false;
this.classNames = ['nav-md', 'scroll-view', 'sidebar-footer'];
}
toggleClass() {
this.navMdClass = !this.navMdClass;
if(this.navMdClass==false){ this.classNames[0] = 'nav-md'; this.classNames[1]="scroll-view"; this.classNames[2]="sidebar-footer"}
if(this.navMdClass==true){ this.classNames[0] = 'nav-sm'; this.classNames[1]=""; this.classNames[2]="sidebar-footer-hide"}
//console.log(this.classNames[0]);
}
}
//child component
import { Component, Input, EventEmitter, OnInit, SimpleChange, OnChanges } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'sidebar',
templateUrl:'sidebar.component.html',
properties: ['cls']
})
export class SidebarComponent{
@Input() classNames:Array<any>;
}
//Parent click event triggers toggleClass
<div class="nav toggle">
<a (click)="toggleClass();" href="#" id="menu_toggle"><i class="fa fa-bars"></i></a>
</div>
//Sidebar selector in parent is where you pass the cls property declared in child component and pass it the classNames array from the parent component
<sidebar [cls]="classNames"></sidebar>
//Child div where target class is
<div class="left_col {{cls[1]}}" >
<div class="{{cls[2]}}" >