我有一个“父” div和一个“子” div,但实际上它们不是。基本上,我想做的是单击“子级”时更改“父级” div的类名。
<div class="dropdown">
<div [style.display]="this.menuofrole.start == true ? 'block' : 'none'" class="item"
(click)="displayStuff($event, this.Org[0],1)">
<i class="fa fa-fw fa-child"></i>Example
</div>
<ng-container *ngFor="let content of this.Org">
<div class="orgDropdown" (click)="displayStuff($event, content,1)">
<a class="">{{content.name}}</a>
</div>
</ng-container>
</div>
我用来更改div类的函数。它可以工作,但我想创建另一个函数来更改“父” div的类。下面的函数更改了单击的div的类。
highlightClickedParentItem(event) {
var parents = event.target.closest(".left").parentElement;
var children = parents.querySelectorAll('.item')
var count = children.length;
for (var i = 0; i < count; i++) {
children[i].className = "item";
}
// checked clicked item icon
var targetParents = event.target.closest(".dropdown");
var children2 = targetParents.querySelectorAll('.item');
var count = children2.length;
for (var i = 0; i < count; i++) {
children2[i].className = "item active";
}
}
答案 0 :(得分:3)
尝试ngClass
,只需点击一下即可触发一个函数并更改变量,如下所示
在HTML中
<div [ngClass]="{'parent-class':item,'child-class':!item}">parent
<div (click)="childClick()">
child
</div>
</div>
在组件中
item:boolean=true
childClick(){
this.item=false
}
答案 1 :(得分:1)
这里是一个示例on Stackblitz 基本上,这是在ngClass指令中,并且可以从html传递参数
export class AppComponent {
cssClass: string;
active: boolean;
changeClass(clss: string): void {
this.cssClass = clss;
this.active = !this.active;
}
}
并在您的html中:
<div [ngClass]="cssClass" [class.active]="active">PARENT</div>
<div (click)="changeClass('new-class')">CLICK 1</div>
<div (click)="changeClass('new-class2')">CLICK 2</div>
确保添加这样的css(仅作为示例)
.new-class {
background: cyan
}
.new-class2 {
background:green;
}
编辑:添加了“活动”类切换