Angular4.x Event (DOM事件和自定义事件详解)(2)

对于 preventDefault() 方法,有一个经典的应用场景。即当我们希望点击链接在新窗口打开页面,但不希望当前页面跳转。这个时候可以使用 preventDefault() 阻止后面将要执行的浏览器默认动作。

<a href="https://i.cnblogs.com/EditPosts.aspx?postid=7792556" >Angular 4.x 事件冒泡</a> <script> document.getElementById('link').onclick = function(ev) { ev.preventDefault(); // 阻止浏览器默认动作 (页面跳转) window.open(this.href); // 在新窗口打开页面 }; </script>

在 Angular 中阻止 DOM 事件冒泡,我们可以使用以下两种方式:

方式一:

<div> <button (click)="$event.stopPropagation(); doSomething()">Click me</button> </div>

方式二:

@Component({ selector: 'exe-app', template: ` <div> <button (click)="doSomething($event)">Click me</button> </div>` }) export class AboutComponent { doSomething($event: Event) { $event.stopPropagation(); // your logic } }

是不是感觉很麻烦,每次都得显式地调用 $event.stopPropagation() 方法。有没有更简便的方法呢?能不能使用声明式的语法?在 Vue 中可以通过声明式的方式,解决我们上面的问题。具体如下:

<!-- the click event's propagation will be stopped --> <a v-on:click.stop="doThis"></a> <!-- the submit event will no longer reload the page --> <form v-on:submit.prevent="onSubmit"></form> <!-- the click event will be triggered at most once --> <a v-on:click.once="doThis"></a>

接下来我们也来基于 Angular 的指令系统,实现上述的功能。最终的使用示例如下:

<div (click)="fromParent()"> <button (click.stop)="fromChild()">Click me</button> </div>

自定义 [click.stop] 指令

@Directive({ selector: '[click.stop]' }) export class StopPropagationDirective { @Output("click.stop") stopPropEvent = new EventEmitter(); unsubscribe: () => void; constructor( private renderer: Renderer2, // Angular 2.x导入Renderer private element: ElementRef) { } ngOnInit() { this.unsubscribe = this.renderer.listen( this.element.nativeElement, 'click', event => { event.stopPropagation(); this.stopPropEvent.emit(event); }); } ngOnDestroy() { this.unsubscribe(); } }

[click.stop] 指令应用

import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <div (click)="fromParent()"> <button (click.stop)="fromChild()">Click me</button> </div> ` }) export class AppComponent { fromChild() { console.log('I am Child'); } fromParent() { console.log('I am Parent'); } }

以上代码成功运行后,当用户点击 Click me 按钮时,浏览器控制台只会输出 I am Child。若把 (click.stop) 改为 (click) ,当用户再次点击 Click me 按钮时,控制台就会输出两条信息。有兴趣的读者,可以亲自验证一下哈。

这篇Angular4.x Event (DOM事件和自定义事件详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a2bf62577fe1670d6a39042ae3b28239.html