我试图使用单击事件打开/关闭类,遇到的问题是,当类在子组件中时,我的单击事件在父组件中。我可以用@输入()装饰器初始化类,但以后无法切换类。
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”中删除大括号
[class.scroll-view]="isClassVisible"