我正在尝试编写一个Angular 2指令来重新创建Foundation Zurb Accordion组件的功能。我试图做一些我认为很简单的事情。我创建了一个指令并添加了一个HostListener来监听点击事件。然而,除了操纵主机元素本身之外,我在HostListener中做的任何事情似乎都被忽略了。我只是试图选择点击的折叠链接的父元素,并将其内容div设置为显示块(参见下面的代码)。我错过了一些基本的东西吗?
import {Component, OnInit, ElementRef, Renderer, HostListener} from '@angular/core';
import {Directive} from "@angular/core/src/metadata/directives";
@Directive({
selector: '[sdAccordion]'
})
export class SdAccordionComponent implements OnInit {
constructor(private el: ElementRef, private renderer: Renderer) {
}
ngOnInit() {
}
@HostListener("document:click", ['$event']) onClick(e){
var clickedEl = e.target;
var classList = clickedEl.classList;
if(classList.contains('accordion-item')){
//This comes back as null but if I try the selector in debig mode in console it works
var contentEl = clickedEl.parentNode.querySelector('.accordion-content');
//this console.log never gets executed
console.log(contentEl);
if(classList.contains('is-active')){
classList.remove('is-active'); //this works
this.renderer.setElementStyle(contentEl, 'display', 'block'); //this does not work
}else{
classList.add('is-active');
this.renderer.setElementStyle(contentEl, 'display', 'none');
}
}
return false;
}
}
<ul class="accordion" sdAccordion>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title">Accordion 1</a>
<div class="accordion-content" data-tab-content>
I would start in the open state, due to using the `is-active` state class.
</div>
</li>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title">Accordion 2</a>
<div class="accordion-content" data-tab-content>
I would start in the open state, due to using the `is-active` state class.
</div>
</li>
</ul>
答案 0 :(得分:0)
您应该使用@hostbinding来更改元素主机状态