Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!--
- HTML, with click events on the <section> and on the <input> element.
- Here the click events are written in Angular, but it doesn't matter, of course. -->
- <h1>Event bubbling demo</h1>
- <section id="wrapper" (click)="onWrapperClick($event)">
- <input type="text" (click)="onInputClick($event)" value="click me" />
- </section>
- // TS file
- class AppComponent
- {
- onWrapperClick(event: Event): void
- {
- // When event bubbling occurs this event handler may be called by another event than expected. In this demo the event.target will be either the SECTION or the INPUT element!
- const t = event.target as HTMLElement; // Unsafe, target may be 'null' at runtime!
- console.log('onWrapperClick');
- console.log(`event.target.localName is "${t.localName}"`); // "input" or "section" !!
- }
- // That's why it's good to use some kind of a type guard like in this method.
- onInputClick(event: Event): void
- {
- const target: EventTarget | null = event.target;
- let inputElem: HTMLInputElement;
- console.log('onInputClick');
- if (!target || !(target instanceof HTMLInputElement))
- {
- console.log('event.target is no HTMLInputElement');
- return;
- }
- inputElem = target; // Now TypeScript doesn't complain because the type is correct!
- console.log(`Target is HTMLInputElement with value "${inputElem.value}"`); // Safe!
- console.log(`event.target.localName "${inputElem.localName}"`); // Always "input".
- //event.stopPropagation(); // Stops the event from bubbling, so it won't reach onWrapperClick, that's a direct possibility here.
- }
- }
- // https://github.com/Amarok24
RAW Paste Data
Copied