我正在尝试使用click事件打开/关闭一个类,我遇到的问题是我的click事件在父组件中,而Class在子组件中。我可以使用@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]" >
答案 0 :(得分:2)
你需要从[class.scroll-view] =“[isClassVisible]”中移除大括号到
[class.scroll-view]="isClassVisible"
答案 1 :(得分:1)
我找到了一个问题的解决方案,这个解决方案涉及将类名作为属性传递给子组件。如果有多个类传递到不同的位置,则可以在适当的区域传递数组属性并输出。
//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]}}" >