Angular 4 触发自定义事件 - EventEmitter 与 dispatchEvent() [英] Angular 4 trigger custom event - EventEmitter vs dispatchEvent()
问题描述
我正在构建指令,它应该在元素进入视口时添加类,并且还将触发自定义事件.我发现了 2 种触发事件的方法 - EventEmitter
和 dispatchEvent()
,两者都可以正常工作.在这种情况下应该使用哪个,为什么?(对代码的任何其他建议表示赞赏)
I'm building directive which should add class when element entered viewport and will also trigger custom event. I found 2 approaches to trigger the event - EventEmitter
and dispatchEvent()
, both works fine. Which should be used in this case and why? (Any other advices on the code appreciated)
import { EventEmitter, Directive, ElementRef, Renderer2, OnInit } from '@angular/core';
import { HostListener } from "@angular/core";
import { Component, Input, Output, Inject, PLATFORM_ID, ViewChild, ViewEncapsulation } from "@angular/core";
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { AfterViewInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Directive({
selector: '[animateOnVisible]',
})
export class AnimateOnVisibleDirective implements AfterViewInit {
@Input() animateOnVisible: string = "fadeInUp";
@Output() enteredViewport: EventEmitter<string> = new EventEmitter();
public isBrowser: boolean;
private enableListener: boolean = true;
constructor(private renderer: Renderer2, private hostElement: ElementRef, @Inject(PLATFORM_ID) private platformId: any) {
this.isBrowser = isPlatformBrowser(platformId);
}
@HostListener("window:scroll", [])
onWindowScroll() {
this.checkScrollPosition();
}
ngAfterViewInit() {
this.checkScrollPosition();
}
private checkScrollPosition() {
if (this.isBrowser && this.enableListener && window.scrollY + window.innerHeight / 2 >= this.hostElement.nativeElement.offsetTop) {
this.renderer.addClass(this.hostElement.nativeElement, this.animateOnVisible);
this.enableListener = false;
//triggering custom event
this.enteredViewport.emit("");
//OR
this.hostElement.nativeElement.dispatchEvent(new Event('enteredViewport', { bubbles: true }));
}
}
}
<div class="animated" [animateOnVisible]="'test'" (enteredViewport)="test()">
推荐答案
EventEmitter
用于 @Output()
可以用于 Angular 事件绑定 >
EventEmitter
is used for @Output()
s that can be used for Angular event binding
<my-component (myEvent)="doSomething()"
dispatchEvent()
触发 DOM 事件,该事件也可以绑定到 Angular @Output()
事件,但也可以冒泡 DOM 树.
dispatchEvent()
fires a DOM event, that also can be bound to like shown for the Angular @Output()
event, but can also bubble up the DOM tree.
前者是 Angular 特有的,对于更有效的意图用例,后者的行为类似于其他 DOM 事件,也可以被非 Angular 代码监听,但效率可能较低.
The former is specific to Angular and for the intented use cases more efficient, the later behaves like other DOM events and can also be listened to by non-Angular code, but might be less efficient.
这篇关于Angular 4 触发自定义事件 - EventEmitter 与 dispatchEvent()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!