gpt4 book ai didi

javascript - 将类添加到 Angular2 指令中的下一个元素

转载 作者:行者123 更新时间:2023-11-29 16:06:11 25 4
gpt4 key购买 nike

我有一个下拉菜单,我想使用 angular2 指令来处理这个下拉菜单的打开/关闭。如何将 open 类添加到 latest-notification div 中。通过知道我的指令应用于 button 标签!

这是我的 html 代码:

<div class="header-notification" (clickOutside)="showPopupNotification = false">
<button appDropdown>
<span [class.has-notification]="hasNotification"></span><icon name="ico_notification"></icon>
</button>
<div class="latest-notification">
<span class="top-pointer"><icon name="arrow-popup"></icon></span>
<div class="wrap">
<ul>
<li *ngFor="let notify of notifications" [class.seen]="notify.seen">
<a>
<avatar src="{{notify.userProfileUrl}}" size="35"></avatar>
<time>{{notify.createAt}}</time>
<h5>{{notify.name}}</h5>
<p>{{notify.message}}</p>
</a>
</li>
</ul>
</div>
</div>
</div>

这是我的指令:

import {Directive, HostBinding, HostListener} from '@angular/core';

@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
private isOpen = false;

@HostBinding('class.open') get opened() {
return this.isOpen;
}

@HostListener('click') open() {
this.isOpen = !this.isOpen;
}
constructor() { }

}

最佳答案

这是我找到的解决方案。我不认为这是正确的方式或最佳方式。但至少它在起作用。

现在通过向按钮指令添加 toggle 指令将被激活,通过单击它,一个名为 open 的类将被添加到下一个元素 最新通知。并且当在按钮外部单击时,open 类将被删除。让我知道你们的想法。

HTML 端:

<div class="header-notification">
<button toggle>
...
</button>
<div class="latest-notification">
...
</div>
</div>

这是指令:

import {Directive, HostListener, ElementRef, Renderer, EventEmitter} from '@angular/core';

@Directive({
selector: '[toggle]'
})
export class DropdownDirective {
isOpen = false;

constructor(private el: ElementRef, private renderer: Renderer) {}

@HostListener('click') open() {
let nextElement = this.el.nativeElement.nextElementSibling;
this.isOpen = !this.isOpen;

if (this.isOpen === true) {
this.renderer.setElementClass(nextElement, "open", true);
} else {
this.renderer.setElementClass(nextElement, "open", false);
}
}

// close dropdown if clicked outside
public clickOutside = new EventEmitter<MouseEvent>();

@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
if (!targetElement) {
return;
}

const clickedInside = this.el.nativeElement.contains(targetElement);

if (!clickedInside) {
this.clickOutside.emit(event);
this.isOpen = false;
let dropdown = this.el.nativeElement.nextElementSibling;
this.renderer.setElementClass(dropdown,"open", false);
}
}


}

关于javascript - 将类添加到 Angular2 指令中的下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com