什么Typescript类型是Angular2事件 [英] What Typescript type is Angular2 event

查看:167
本文介绍了什么Typescript类型是Angular2事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在html文件中有以下按钮

If I have the following button in an html file

<button (click)="doSomething('testing', $event)">Do something</button>

另外,在相应的组件中,我有这个功能

Also, in the corresponding component, I have this function

doSomething(testString: string, event){
    event.stopPropagation();
    console.log(testString + ': I am doing something');
}

是否有适当的类型应分配给 $ event 输入?
事件参数本身是一个对象,但是如果我将它分配给一个类型对象,我会收到一个错误

Is there a proper type that should be assigned to the $event input? The event parameter itself is an object, BUT if I assign it to a type object, I get an error


Property'类型对象上不存在stopPropogation

Property 'stopPropogation' does not exist on type object

那么,Typescript会考虑 $ event 输入?

So, what does Typescript consider the $event input?

推荐答案

根据@AlexJ的建议

As suggested by @AlexJ

您通过 $ event 传递的事件是一个DOM事件,因此您可以使用 EventName 作为类型。

The event you passed through $event is a DOM event, therefore you can use the EventName as the type.

在您的情况下,此事件是 MouseEvent ,文档说,引用

In your case this event is a MouseEvent, and the docs says, quoting


MouseEvent 接口表示由于用户与指点设备(例如鼠标)交互而发生的事件。使用此界面的常见事件包括 click,dblclick,mouseup,mousedown

The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click, dblclick, mouseup, mousedown.

在所有这些情况下,你'我得到一个 MouseEvent

In all those cases you'll get a MouseEvent.

另一个例子:如果你有这个代码

Another example : if you have this code

<input type="text" (blur)="event($event)"

当事件触发时,您将获得 FocusEvent

When the event triggers you'll get a FocusEvent.

所以你可以做到这一点非常简单,控制台登录事件,你会看到一条类似于这个消息,我们有事件名称

So you can do it really simple, console log the event and you'll see a message similar to this one that'll we have the event name

FocusEvent {isTrusted: true, relatedTarget: null, view: Window, detail: 0, which: 0…}

您可以随时访问现有活动列表的文档。

You can always visit the docs for a list of existing Events.

修改

您还可以检查TypeScript dom.generated.d.ts ,其中包含所有类型的内容。在您的情况下 stopPropagation() 事件 ,由 MouseEvent 扩展。

You can also check for TypeScript dom.generated.d.ts with all the typings ported. In your case stopPropagation() is part of Event, extended by MouseEvent.

这篇关于什么Typescript类型是Angular2事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆