Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - What Typescript type is Angular2 event

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');
}

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' does not exist on type object

So, what does Typescript consider the $event input?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As suggested by @AlexJ

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

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

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.

In all those cases you'll get a MouseEvent.

Another example : if you have this code

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

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.

Edit

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...