<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shijir Tsogoo on Medium]]></title>
        <description><![CDATA[Stories by Shijir Tsogoo on Medium]]></description>
        <link>https://medium.com/@shijirtsogoo?source=rss-e1852758089c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X9GFnDyjj-IJO7G1.jpg</url>
            <title>Stories by Shijir Tsogoo on Medium</title>
            <link>https://medium.com/@shijirtsogoo?source=rss-e1852758089c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:57:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shijirtsogoo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Four ways of listening to DOM events in Angular (Part 3: Renderer2.listen)]]></title>
            <link>https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-3-renderer2-listen-14c6fe052b59?source=rss-e1852758089c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c6fe052b59</guid>
            <category><![CDATA[renderer2]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[dom-events]]></category>
            <category><![CDATA[vmware]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Shijir Tsogoo]]></dc:creator>
            <pubDate>Tue, 19 May 2020 23:56:30 GMT</pubDate>
            <atom:updated>2020-08-30T23:42:56.875Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous two posts, we did a deep-dive into how we could listen to DOM events in an Angular app through the following two methods:</p><ol><li><a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-1-event-binding-3ec7e9f51a1d"><strong>Event Binding</strong></a>: One-way data binding, in which information is sent from a component’s template to the component’s class</li><li><a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-2-hostlistener-1b66d45b3e3d"><strong>@HostListener</strong></a>: Angular decorator that handles events on the host element of a component or directive</li></ol><p>As we covered these methods, we learned how much they simplify the process of listening to DOM events while also providing many other nifty little features. However, a common aspect of these two methods is that they are both completely tied to their template or host element, which creates certain limitations. In this post, we will go over what those limitations are and how we can use Angular’s <a href="https://angular.io/api/core/Renderer2#listen">Renderer2.listen</a> method to resolve them as well as many other cases where you can put it into use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*RaZ1eUz15e8ELop0sZlM5Q.jpeg" /></figure><h4><em>What is Renderer2 in Angular?</em></h4><p>As Angular is a multi-platform framework, it offers secure and easy-to-use tools that manage and abstract away differences across browsers and platforms. One of those tools is <a href="https://angular.io/api/core/Renderer2#renderer2">Renderer2</a>, which is an Angular’s built-in service that provides APIs for interacting with and manipulating DOM elements.</p><p>As different environments such as web browsers, web-workers, and server-side rendering have different implementations of DOM, these Renderer2 APIs are built to manage those differences and yield consistent results. Note that Renderer2 not only facilitates manipulating HTML elements, but also the types of XML, SVG, etc. To learn more about the intricacies of Renderer2, I recommend taking a closer look at its <a href="https://github.com/angular/angular/blob/master/packages/platform-browser/src/dom/dom_renderer.ts">source code</a>.</p><h4>Angular Renderer2.listen <em>vs Element.addEventListener</em></h4><p>Let’s recall how we add and remove event listeners using native DOM APIs. If we want to listen to a mousemove event on some native DOM element and invoke its callback function, onMouseMove, we would call the .addEventListener in the following way:</p><pre>nativeElement.addEventListener(&quot;mousemove&quot;, onMouseMove);</pre><p>To remove this event listener, we need to call .removeEventListener on the same button element with the <strong>exact same matching parameters</strong>:</p><pre>nativeElement.removeEventListener(&quot;mousemove&quot;, onMouseMove);</pre><p>But it’s very easy to blunder when you try to <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#Matching_event_listeners_for_removal">match event listeners for removal</a>. <strong>Properly removing an event listener that is added manually is crucial as it prevents memory leaks as well as performance drag on your application.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*p_kZspv8piN3EA73y5_Hcg.jpeg" /></figure><p>With Renderer2.listen, it becomes much easier to clean up event listeners. Take a look at its API pattern:</p><pre><a href="https://angular.io/api/core/Renderer2"><strong>Renderer2</strong></a><strong>.listen(</strong>target: <em>any</em>, eventName: <em>string</em>, callback: <em>(event: any) =&gt;  boolean | void</em> <strong>)</strong>:<strong> () =&gt; void;</strong></pre><p>You can see that Renderer2.listen method itself returns another method with the type of <strong>() =&gt; void</strong>. That returned method is used for removing the event listener. This is much simpler than trying to match event listeners for removal. Just save the returned method’s reference to a variable or property, and call that whenever you need to remove the listener. Let’s see how this would play out in a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/197023616578efe7071147fd663656f4/href">https://medium.com/media/197023616578efe7071147fd663656f4/href</a></iframe><p>In the example above, I am trying to listen to the mousemove event on document. So I’ve imported Renderer2 into my component first and then added the mousemove event listener todocument through Renderer2.listen in theOnInit cycle.</p><p>Note that when I add the event listener, I’m saving the returned method to the unlistener property which will be called later to remove the event listener in the OnDestroy cycle, which gets called when the component gets destroyed.</p><p>Another important thing to note here is that I’ve passed document not as an object, but as a string. If we pass document as an object, we will see the following error when we try to run our app in a server-side environment:</p><pre>ERROR ReferenceError: document is not defined</pre><p>This is because there are no global objects such as window or document in environments other than web browsers. We could resolve this issue by checking what environment this code is running in. But with Renderer2.listen, we can simply pass either string &quot;document&quot; or &quot;window&quot; and let Angular do the checking for us and adapt to the environment that it’s running in.</p><h4>Angular Renderer2.listen vs Event Binding</h4><p>Let’s see an example where you want to create Drag and Drop functionality using generic mousedown, mousemoveand mouseup events. This example below accomplishes just that through template event binding:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasic-dnd-with-template-binding%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasic-dnd-with-template-binding&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/430f215f6467eff2e09322ad3829d01e/href">https://medium.com/media/430f215f6467eff2e09322ad3829d01e/href</a></iframe><p>The main idea here is that dragging should start with a mousedown event on the draggable element. Only after that first mousedown should we start responding to the mousemove event(s) on the document, as the element could be dragged anywhere on the document. To make sure mousedown is registered first, we check if the draggableEl property is defined in the mousemove event’s handler. On themouseup event, we reset the whole process by simply assigning null to the draggableEl property.</p><p>As you can see in the demo above, the code looks extremely simple… but there are some serious issues that we need to fix. For one, we’ve added three active event listeners on the draggable element that will always be listening until the target element gets removed from the DOM. To make matters worse, we are listening to mousemove and mouseup events globally because they are defined on document. So we are continuously listening and trying to respond to all mousemove and mouseup events on the entire app — and it doesn’t end there! Every time these events fire, they also trigger Angular’s change detection throughout all components and directives, which could cause significant performance deterioration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*X3A1dKgWthdHeQ_aPUQPTQ.jpeg" /></figure><p>The first step to solve the above-mentioned problems is to add the mousemove and the mouseup event listeners <strong>inside</strong> themousedown event listener’s handler. However, we cannot accomplish that with event bindings as they are inlined to their template elements permanently. In the case of using @HostListener, we would still face the same problem.</p><p>Hence, we need to use Renderer2.listen which allows us to dynamically add and remove listeners when only certain conditions are met. In our case, we need to add the mousemove and the mouseup event listeners to document only when the mousedown event is registered on the draggable element. In the example below, I’ve demonstrated how to do that using Renderer2.listen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasic-dnd-with-renderer2-listen%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasic-dnd-with-renderer2-listen&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5971d4c313024d7a70703dfa6b48c624/href">https://medium.com/media/5971d4c313024d7a70703dfa6b48c624/href</a></iframe><p>The code is a bit more involved compared to what we saw with the event binding example. Here, the important thing to pay attention to is how we are adding and removing event listeners. Now we have only one active listener on the draggable element instead of three as the event listeners on mousemove and mouseup are nested inside the mousedown event listener’s handler. And you can also see that the event listeners on mousemove and mouseup are removed when the mouseup event fires.</p><p>But we have to address another issue I’ve briefly mentioned earlier: every time one of these mousedown, mousemove, and mouseup events fire, Angular change detection would also run. Remember that Angular change detection runs through all components and directives in the following three cases:</p><ul><li>When event listeners respond to their target DOM events</li><li>When setTimeout() or setInterval() executes</li><li>When ajax requests respond</li></ul><p>This is especially concerning as we are dealing with an event such as mousemove that fires on each pixel movement you make with your mouse. So Angular change detection might be unnecessarily triggered thousands of times. Fortunately, Angular lets us run our code outside of its change detection zone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*HDvRl_CKanRqSnWamLrYSw.jpeg" /></figure><p>What we need to do is to make use of <a href="https://angular.io/api/core/NgZone">NgZone</a>, which is a service that lets you run your code inside or outside of the Angular zone. To run our code outside of the Angular zone, we need to use the following API pattern:</p><pre><strong>NgZone.runOutsideAngular</strong>&lt;T&gt;(fn: (...args: any[]) =&gt; T): T</pre><p>We also need to be careful while using the API above because any data binding changes made outside of the Angular zone will not take effect unless you are directly manipulating the DOM. In the case of our Drag and Drop example, we could add mousemove event listener outside of the Angular zone:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e615c5a5fc5a4fdbe207ccf5da5d68d7/href">https://medium.com/media/e615c5a5fc5a4fdbe207ccf5da5d68d7/href</a></iframe><p>As you can see, I’ve placed themousemove event listener entirely inside this.ngZone.runOutsideAngular‘s callback method to prevent change detection from running. But for the mousedown event, change detection would still run when the event fires as this.ngZone.runOutsideAngular is used inside its handler. That’s an important difference to keep in mind. This is the reason why we cannot suppress change detection if we add event listeners through Event Binding or @HostListener methods. Hence, if you need to listen to events that fire frequently many times such mousemove, touchmove, or scroll, consider using Renderer2.listen with this.ngZone.runOutsideAngular.</p><h4>Bonus tip:</h4><p>Another cool feature Renderer2.listen offers is that you can listen to DOM events and also listen to Angular Pseudo Events. That means you could do this:</p><pre>Renderer2.listen(nativeElement, &quot;<strong>keyup.enter</strong>&quot;, event =&gt; { ... })</pre><pre>Renderer2.listen(nativeElement, &quot;<strong>keydown.esc</strong>&quot;, event =&gt; { ... })</pre><pre>Renderer2.listen(nativeElement, &quot;<strong>keyup.arrowup</strong>&quot;, event =&gt; { ... })</pre><pre>Renderer2.listen(nativeElement, &quot;<strong>keyup.arrowdown</strong>&quot;, event =&gt; { ... })</pre><p>If you want to learn more about Angular Pseudo Events, please refer to <a href="https://medium.com/claritydesignsystem/angular-pseudo-events-d4e7f89247ee">this article</a>.</p><h3>Let’s recap — Key Takeaways:</h3><ul><li><a href="https://angular.io/api/core/Renderer2#renderer2">Renderer2</a> is Angular’s built-in service that provides APIs for interacting with and manipulating DOM elements. Manipulating DOM elements through Renderer2 yields consistent results across different web browsers as well as environments.</li><li>With Renderer2.listen, it becomes much easier to clean up event listeners. You no longer need to <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#Matching_event_listeners_for_removal">match event listeners for removal</a>.</li><li>Unlike Event Binding or @HostListener methods, with Renderer2.listen, you can manage complex event listeners by adding and removing them on specific conditions.</li><li>You can leverage Renderer2.listen together with NgZone.runOutsideAngular to suppress Angular change detection.</li></ul><p>Stay tuned for the next blog post of this series, which will be on RxJS and how we could use it to listen to DOM events in Angular app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c6fe052b59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-3-renderer2-listen-14c6fe052b59">Four ways of listening to DOM events in Angular (Part 3: Renderer2.listen)</a> was originally published in <a href="https://medium.com/claritydesignsystem">Clarity Design System</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things are often not what they seem]]></title>
            <link>https://medium.com/@shijirtsogoo/things-are-often-not-what-they-seem-78fd0ed30625?source=rss-e1852758089c------2</link>
            <guid isPermaLink="false">https://medium.com/p/78fd0ed30625</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[perspective]]></category>
            <category><![CDATA[disguises]]></category>
            <category><![CDATA[opportunity]]></category>
            <dc:creator><![CDATA[Shijir Tsogoo]]></dc:creator>
            <pubDate>Sun, 17 Mar 2019 02:31:16 GMT</pubDate>
            <atom:updated>2019-03-17T02:45:30.726Z</atom:updated>
            <content:encoded><![CDATA[<p>We associate pleasure with well-being, and pain with danger. But things that make you feel comfortable and cozy could cause the most harms to your life. Conversely, things that hurt you give you opportunities to become stronger, healthier, and more intelligent. We associate luck with success and prosperity. But luck that would come too early before its righteous time is not luck but could be a curse in disguise. On the other hand, misfortunes often give you opportunities to reflect on what could be improved in your life and reveal what habits and thought processes had led you to them. Wasting those opportunities will lead you to the same misfortunes or another. This is why life is a tricky bastard. But also, this is exactly what makes life interesting and beautiful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78fd0ed30625" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four ways of listening to DOM events in Angular (Part 2: @HostListener)]]></title>
            <link>https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-2-hostlistener-1b66d45b3e3d?source=rss-e1852758089c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b66d45b3e3d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vmware]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[clarity-design-system]]></category>
            <dc:creator><![CDATA[Shijir Tsogoo]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 23:06:00 GMT</pubDate>
            <atom:updated>2020-09-21T04:19:10.290Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article of this series, we talked about what Angular Event Binding is and how it can be used in a variety of different cases. We learned that the primary purpose of <a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-1-event-binding-3ec7e9f51a1d">Angular Event Binding</a> is to listen to events <strong><em>inside a component’s template</em></strong>. So now how about listening to events <strong><em>on the host element that wraps the component’s template</em></strong>? How can we do that properly in Angular apps? That’s the very question we will answer in this article.</p><p>Before diving directly into listening to DOM events on a host element, I think we need to touch on what a host element is. The concept of host element applies not only to <a href="https://angular.io/guide/architecture-components">components</a> but also <a href="https://angular.io/guide/attribute-directives">attribute directives</a>.</p><blockquote>In a component, the host element is the outer most shell element that contains the template, and its tag name is your chosen selector string in the component’s configuration.</blockquote><p>Let’s take a look at a simple example here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a4680420e84fc95bb1f64b61147d550/href">https://medium.com/media/7a4680420e84fc95bb1f64b61147d550/href</a></iframe><p>In the example above, I’ve created a component called BaconIpsum which provides a <a href="https://baconipsum.com/">bacon ipsum dummy text</a> through its template. Angular renders this using the selector string bacon-ipsum whose content is the template. So here, the &lt;bacon-ipsum&gt; element is the component’s host element.</p><blockquote>As for an attribute directive, you place it on an existing element in your application and that very element becomes the host element of the directive.</blockquote><p>Here, in the example below, I created a bare-bone directive with a selector string onlyMyBacon:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec184e352d858c9d9596d774511f5622/href">https://medium.com/media/ec184e352d858c9d9596d774511f5622/href</a></iframe><p>Any element that I place this onlyMyBacon directive on will be the directive’s host element. If you go back to the first example, you would find that I have placed the directive on the&lt;mark&gt;element inside the component’s template.</p><p>As Angular developers, we will certainly encounter many instances in which we need to listen to events on the host element whether it’s of a component or attribute directive. That’s where <a href="https://medium.com/@HostListener">@HostListener</a> comes in handy.</p><p>Let’s see an example of using @HostListener to listen to a DOM event in a directive. I will use and expand my previous directive example with @HostListener:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a23d27a43547c8bdd6d9262d9f016b2a/href">https://medium.com/media/a23d27a43547c8bdd6d9262d9f016b2a/href</a></iframe><p>Now any element with the onlyMyBacon directive on will display an alert “<em>Don’t touch my bacon!</em>” when you hover over with your mouse cursor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*-P6X92tj9lHRsAn18-aoCg.jpeg" /></figure><p>As described before, this directive will turn any element that it is placed on into its host element and it set its mouseenter event listener on the host element through @HostListener . As you can see in the code, you would declare the @HostListener decorator method with the DOM event passed in as the argument, followed by its event handler method.</p><p>Check out the aforementioned code snippets in the live demo:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbacon-ipsum%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbacon-ipsum&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/62762482d392ffb7b605084068a1f31d/href">https://medium.com/media/62762482d392ffb7b605084068a1f31d/href</a></iframe><h4>But why do we need @HostListener here?</h4><p>You might ask at this point, why is it necessary to use @HostListener? Why do we need to bother to learn another higher-level API in Angular just to listen to DOM events? Why can’t we just stick to our traditional way of listening to events with our trusty Element.addEventListener method? Well, you can do that and avoid using @HostListener. But to achieve the same result, our example would turn into the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fdd9bf4fabfe80097106d21212d04c5/href">https://medium.com/media/6fdd9bf4fabfe80097106d21212d04c5/href</a></iframe><p>Now, in the example above, we are dealing with a lot more things compared to our first example. We had to first inject the directive’s element reference to the constructor, access its native DOM element, and add our event listeners to the host element. And if you remember, in my previous post on <a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-1-event-binding-3ec7e9f51a1d">Angular Event Binding</a>, I’ve stated that it’s never a good idea to access DOM elements and their methods or properties directly, let alone manipulating them as it creates problems with Angular’s complex change detection system as well as web workers. And touching the DOM elements directly is one of the most common mistakes Angular Developers make.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*069GZAfO9I3e87RYRNwi4Q.jpeg" /></figure><p>On top of that, you can see that we had to implement Angular’s lifecycle hook methods to manually add the listener when the directive is initialized and remove it when it gets destroyed. When you manually add a listener to a DOM element, always make sure to remove the listener later when you no longer need it. Otherwise, it could potentially lead to memory leak problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*bZsObT6IGJiS36zs0Iv_WQ.jpeg" /></figure><p>So by using @HostListener, you can let Angular do the proper removals and clean up for you, and your code will also remain clean, concise, and declarative.</p><h4>Passing and accessing arguments in the event handler method</h4><p>With @HostListener, you can access the event payload object through<strong>$event</strong> keyword:</p><pre>@HostListener(&#39;mouseenter&#39;, <strong>[&#39;$event&#39;]</strong>)<br>onMouseEnter(event: any) {    </pre><pre>  // Logs the id of the element <br>  // where the event is originally invoked.     <br>  console.log(event.target.id);<br>}</pre><p>All arguments you would like to access in the event handler method should be included in that array first. Note that, in the code snippet above, it’s still passing an object despite being wrapped inside quotes. But If you would like to pass an actual string directly as an argument, that should be inside nested quotes as shown below:</p><pre>@HostListener(&#39;mouseenter&#39;, [<strong>&#39;&quot;hello!&quot;&#39;</strong>, &#39;$event&#39;]) onMouseEnter(greeting: string, event: any) {</pre><pre>  // Logs the string argument, &quot;hello!&quot;<br>  console.log(greeting);</pre><pre>  // Logs the id of the element <br>  // where the event is originally invoked.    <br>  console.log(event.target.id);<br>}</pre><p>You can also pass a specific property from an object. For instance, in the snippet below, it’s directly passing <em>the target element’s id </em>that the event is originated from by specifying the nested properties from the <strong>$event</strong> object:</p><pre>@HostListener(&#39;mouseenter&#39;, <strong>[&#39;$event.target.id&#39;]</strong>) <br>onMouseEnter(id: string) {</pre><pre>  // Logs the id of the element <br>  // where the event is originally invoked.  <br>  console.log(id);<br>}</pre><h4>Listening to events originating inside and outside the directive</h4><p>One of the most important concepts in handling events is event delegation or event bubbling. If you are not familiar with these terms or concepts, I highly recommend reading <a href="https://davidwalsh.name/event-delegate"><em>How JavaScript Event Delegation Works by David Walsh</em></a>. I have also gone over how these concepts apply to Angular event binding in the previous post. As with @HostListener, you can also catch and respond to events that originated in any nested or child element as they bubble up to the directive. In the example below, I placed the clickCatcher directive on the very parent element, ul . However, you can see that it registers click events from not only its own host element but also from its children items:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fzone-detector-no-hostlistener-xkpmco%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fzone-detector-no-hostlistener-xkpmco&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0377ba83082f5c3ae90bf83604a6a0bd/href">https://medium.com/media/0377ba83082f5c3ae90bf83604a6a0bd/href</a></iframe><p>Also, unless the propagations are stopped on the way up, any DOM event eventually bubbles up to the global root elements such as document or window. So you can use @HostListener to set your listeners on the global element to catch any event that is fired on any node element in your application:</p><pre>@HostListener(&#39;<strong>window:click</strong>&#39;, [&#39;$event.target&#39;])<br>onClick(targetElement: string) {</pre><pre>  console.log(`You clicked on`, targetElement);<br>}</pre><p>However, it’s only recommended to set event listeners on window or document if you are sure that the directive will be used only once or very few times across the application. Having many directives that listen to the same event on the global elements could eventually hurt the performance of your application.</p><p>Lastly, just like in Angular event binding, you can also use Angular Pseudo-Events with @HostListener. I have written a blog post on Angular Pseudo-Events and touched on how to use them with @HostListener so <a href="https://medium.com/claritydesignsystem/angular-pseudo-events-d4e7f89247ee">check out that blog post</a> too. Stay tuned for the next blog posts on event listeners as I explore the other methods of listening to DOM events in Angular. Okay, now done with @HostListener!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*vC_4ZQEm7bJmHPNtpaWiYQ.gif" /></figure><h4>Let’s recap — Key Takeaways:</h4><ul><li>@HostListener is Angular’s decorator method that’s used for listening to DOM events on the host element of both component and attribute directives.</li><li>@HostListener sets the listeners once the directive is initialized and removes them automatically once the directive gets destroyed.</li><li>@HostListener catches and listens to events from children or nested elements when they bubble up to the host element. Moreover, you can listen to events on global elements, but you should do so sparingly for performance reasons.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b66d45b3e3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-2-hostlistener-1b66d45b3e3d">Four ways of listening to DOM events in Angular (Part 2: @HostListener)</a> was originally published in <a href="https://medium.com/claritydesignsystem">Clarity Design System</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Pseudo-Events]]></title>
            <link>https://medium.com/claritydesignsystem/angular-pseudo-events-d4e7f89247ee?source=rss-e1852758089c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e7f89247ee</guid>
            <category><![CDATA[vmware]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[clarity-design-system]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Shijir Tsogoo]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 17:10:52 GMT</pubDate>
            <atom:updated>2018-09-15T00:08:21.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular offers a nifty little feature to facilitate the process of listening to keyboard events. Even though it’s mentioned in Angular’s template binding documentation very briefly as <a href="https://angular.io/guide/user-input#key-event-filtering-with-keyenter">pseudo-event</a>, it hasn’t been further documented anywhere else. Before anything else, to see what problem Angular pseudo-event solves, let’s take a look at this simple task where you need to add an <strong><em>UNDO</em></strong> command to a toggle-switch checkbox. The <strong><em>UNDO</em></strong> command should revert the user’s last choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*oW0Lv-52HDLZmXPxch4DpA.jpeg" /></figure><p>Just like how we execute the <strong><em>UNDO</em></strong> command on our computers, the command should respond to <strong>CTRL+Z </strong>key combination. The example below shows how we can accomplish the task without pseudo-events:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fundo-without-pseudo-events%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fundo-without-pseudo-events&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c7eb820256a4ddf55b60a7fcf356640/href">https://medium.com/media/3c7eb820256a4ddf55b60a7fcf356640/href</a></iframe><p>As you can see in the example above, I am looking at the KeyboardEvent.key to check which keystroke is hit. There are also other properties of KeyboardEvent that you can use to check and catch keystrokes such as KeyboardEvent.key, KeyboardEvent.charCode, KeyboardEvent.keyCode or KeyboardEvent.which. However, some of them have been deprecated or browser support for them will vary from one browser to another. Also, the more key combinations we need to listen to, the more convoluted the syntax becomes.</p><p>Angular pseudo-events will free you from all the concerns above. Through pseudo-events, Angular allows you to directly bind to a specific keystroke or keystroke combination. That means a keyboard event will be only fired on that specific key or key combination instead of on all key events. The following is an example of how to declare pseudo-events in your template:</p><pre>&lt;input <strong>(keyup.enter)</strong>=&#39;...responds to enter...&#39; /&gt;</pre><pre>&lt;input <strong>(keydown.esc)</strong>=&#39;...responds to escape...&#39; /&gt;</pre><pre>&lt;input <strong>(keyup.shift.f)</strong>=&#39;...responds to shift+f...&#39; /&gt;</pre><p>Now let’s see how Pseudo-Events can facilitate us to listen to <strong>CTRL+Z</strong> key combination:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fundo-with-pseudo-event%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fundo-with-pseudo-event&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/080f748c3d07af8b19bde5eeab2acda8/href">https://medium.com/media/080f748c3d07af8b19bde5eeab2acda8/href</a></iframe><p>As you can see, we now no longer need to check which keystrokes are registered because we specify the combination of keys that our handler should respond to, and the syntax has become more declarative.</p><h4>Using Angular Pseudo-Events in @HostListener</h4><p>Just like any other DOM events, you can listen to pseudo-events through @HostListener:</p><pre>@HostListener(&#39;<strong>keydown.control.z</strong>&#39;) undo(event: KeyboardEvent) {<br> <br>  // responds to control+z</pre><pre>}</pre><p>Of course, if a host element is not focusable or you need to catch a keyboard event regardless of where it originated, you could bind the event to a global element like this:</p><pre>@HostListener(&#39;<strong>document:keydown.control.z</strong>&#39;) undo(event: KeyboardEvent) {<br> <br>  // responds to control+z</pre><pre>}</pre><h4>Key names in Pseudo-Events</h4><p>Now take a look at this example of a pseudo-event key combination:</p><pre>&lt;input (<strong>keydown.control.shift.z</strong>)=&#39;...&#39;/&gt;</pre><p>You might be wondering where these key names such as control, shift, and z are coming from. They are not unique to Angular pseudo-events. In fact, <strong>they are case-insensitive key property values of </strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key"><strong>KeyboardEvent</strong></a>. If you want to see a comprehensive list of keyboard event key property values, please see <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values">this reference</a>. Now let’s go over the key values that are available in Angular pseudo-events.</p><p><strong>Modifier Keys</strong></p><p>Modifier keys include Shift, Control, Alt(Option), and Meta(Command). I will refer to any other key as a non-modifier key from here on. Modifier key pseudo-events look like this:</p><pre>&lt;input (<strong>keyup.control</strong>)=&#39;...respond to ctrl/control...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.alt</strong>)=&#39;...respond to alt/option...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.shift</strong>)=&#39;...respond to shift...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.meta</strong>)=&#39;...respond to command...&#39; /&gt;</pre><p>There are several points that you need to keep in mind to use modifier keys in Angular pseudo-events. First, <strong>any <em>key combination</em> must have at least one modifier key, but only one non-modifier key</strong>. For example, the following case wouldn’t work as the combination consists of only letter keys:</p><pre>&lt;input (<strong>keyup.a.z</strong>)=&#39;...respond to a+z...&#39; /&gt;</pre><p>Second, <strong>a non-modifier key must be always defined at the very end of the key combination.</strong> The following is a proper placement of a non-modifier key as the <strong>Z </strong>(non-modifier key) is defined at the end:</p><pre>&lt;input (<strong>keydown.control.z</strong>)=&#39;...responds to control+z...&#39; /&gt;</pre><p>In contrast, the example below shows an improper placement of a modifier key:</p><pre>&lt;input (<strong>keydown.z.control</strong>)=&#39;...won&#39;t respond at all...&#39; /&gt;</pre><p>Third, <strong>the sequence of modifier keys themselves doesn’t matter</strong>. So you can place them in any order that suits your needs. Both of the examples below show valid use cases:</p><pre>&lt;input (<strong>keydown.shift.control.z</strong>)=&#39;...responds to shift+control+z...&#39; /&gt;<br>&lt;input (<strong>keydown.control.shift.z</strong>)=&#39;...responds to control+shift+z...&#39; /&gt;</pre><p>Let’s move onto the examples of non-modifier keys.</p><p><strong>Functional keys</strong></p><pre>&lt;input (<strong>keyup.f5</strong>)=&#39;...responds to F5...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.f12</strong>)=&#39;...responds to F12...&#39; /&gt;</pre><p><strong>Number and letter keys</strong></p><pre>&lt;input (<strong>keyup.0</strong>)=&#39;...responds to 0...&#39; /&gt;<br><br>&lt;input (<strong>keyup.9</strong>)=&#39;...responds to 9...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.a</strong>)=&#39;...responds to a...&#39; /&gt;<br><br>&lt;input (<strong>keyup.z</strong>)=&#39;...responds to z...&#39; /&gt;</pre><p><strong>Arrow keys</strong></p><pre>&lt;input (<strong>keyup.arrowup</strong>)=&#39;...responds to arrowup...&#39; /&gt;<br><br>&lt;input (<strong>keyup.arrowright</strong>)=&#39;...responds to arrowright...&#39; /&gt;</pre><p><strong>Other keys</strong></p><pre>&lt;input (<strong>keyup.enter</strong>)=&#39;...responds to enter...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.esc</strong>)=&#39;...responds to escape...&#39; /&gt; </pre><pre>&lt;input (<strong>keyup.escape</strong>)=&#39;...responds to escape...&#39; /&gt;<br><br>&lt;input (<strong>keyup.backspace</strong>)=&#39;...responds to backspace...&#39; /&gt;</pre><pre>&lt;input (<strong>keyup.tab</strong>)=&#39;...responds to tab...&#39; /&gt;</pre><p>Currently, there are only two keys that are an exception to this: <em>Dot</em> and <em>Space</em>. When you hit the dot key on your keyboard, its <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key">KeyboardEvent.key</a> property value would be &quot;.&quot;. But, as you can imagine, it would be syntactically improper to use it in a pseudo-event as dots function as a separator in key combinations. That’s why it’s mapped to the &quot;dot&quot; keyword. So you would do the following to properly listen to the <em>Dot</em> keystroke:</p><pre>&lt;input (<strong>keydown.dot</strong>)=&#39;...responds to dot...&#39;/&gt;</pre><p>…instead of:</p><pre>&lt;input (<strong>keydown..</strong>)=&#39;...won&#39;t respond at all...&#39;/&gt;</pre><p>The same thing goes for the <em>Space</em> keystroke. As its <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key">KeyboardEvent.k</a>ey property value is &quot; &quot; , it’s mapped to the &quot;space&quot; keyword for better readability. So rather than this:</p><pre>&lt;input (<strong>keydown. </strong>)=&#39;...won&#39;t respond at all...&#39;/&gt;</pre><p>You would define the key as below:</p><pre>&lt;input (<strong>keydown.space</strong>)=&#39;...won&#39;t respond at all...&#39;/&gt;</pre><p>Unfortunately, Angular pseudo-events are still missing this kind of mapping for most of the symbol keys such as <em>Minus</em>, <em>Equal, Slash, BracketLeft, BracketRight, Backquote, etc. </em>As they are symbol keys, they result in very poor readability or sometimes even break the binding itself. For example, if I want to listen the <em>Minus</em> keystroke, I can only do that as follows:</p><pre>&lt;input (<strong>keydown.-</strong>)=&#39;...responds to minus...&#39;/&gt;</pre><p>As you can see, it looks rather odd or syntactically wrong, but it works. It would be more readable or at least easier on the eyes if it were mapped to its declarative keyword:&quot;minus&quot;. How about the <em>Equal</em> keystroke?</p><pre>&lt;input (<strong>keydown.=</strong>)=&#39;...breaks the binding...&#39;/&gt;</pre><p>If you try to listen to the <em>Equal</em> keystroke as shown above, it will break your template binding because there is no &quot;equal&quot; keyword mapping for it either.</p><p>Despite a few minor shortcomings with symbol keys, Angular pseudo-events are an awesome feature that covers most of the use cases of listening to keyboard events. I believe that using it makes the process of implementing keyboard accessibility and interactivity much easier in any Angular application.</p><p>After reading this blog post, I hope you have gained a few ideas and insights about Angular pseudo-events. On a related note, if you are interested in learning more about events and different ways of listening to them in Angular, I have started a blog series on them. Checkout the first post of that series here: <a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-1-event-binding-3ec7e9f51a1d">Four ways of listening to DOM events in Angular (Part 1: Event Binding)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e7f89247ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/claritydesignsystem/angular-pseudo-events-d4e7f89247ee">Angular Pseudo-Events</a> was originally published in <a href="https://medium.com/claritydesignsystem">Clarity Design System</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four ways of listening to DOM events in Angular (Part 1: Event Binding)]]></title>
            <link>https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-1-event-binding-3ec7e9f51a1d?source=rss-e1852758089c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec7e9f51a1d</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vmware]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[clarity-design-system]]></category>
            <dc:creator><![CDATA[Shijir Tsogoo]]></dc:creator>
            <pubDate>Thu, 24 May 2018 13:24:28 GMT</pubDate>
            <atom:updated>2020-05-20T00:03:18.123Z</atom:updated>
            <content:encoded><![CDATA[<p>Listening to DOM events and keeping Angular application performant can be challenging. Angular offers several methods to listen to events. By examining those available options and methods, we can understand and be aware of the characteristics that each one has. The four options for listening and reacting to DOM events that will be covered in this blog series are:</p><ol><li><strong>Event Binding</strong>: One-way data binding, in which information is sent from a component’s template to the component’s class</li><li><strong>@HostListener</strong>: Angular decorator that handles events on the host element</li><li><strong>Renderer2:</strong> Using Renderer2 .listen() method for a target event and element</li><li><strong>RxJS: </strong>Using RxJS .fromEvent() operator that turns events into observable sequences</li></ol><blockquote>Give a fool a hammer and everything becomes a nail.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*yzg9ei2Hv9Xg-EEw8NIHzQ.jpeg" /></figure><p>There is no such tool that works for all of the use cases. Listening to DOM events is no different. In this series, as we delve into those four options, keep that in mind because each of the methods we look into has its own benefits and trade-offs. But for this blog post, let’s dive into Angular event binding.</p><h4><strong>Event Binding</strong></h4><p>In event binding, information flows from elements in a component template to the corresponding component’s class. With event binding, you don’t need to give the target element an identifier in order to access and attach your listeners to it because you are dealing with the target event and the target element directly in the template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*KW8ia5wHC2IR8Su2OvKy6A.jpeg" /></figure><p>So it is the simplest way of listening to events on elements in a component template. Let’s look at a simple example of event binding:</p><pre> &lt;button (click)=&quot;handleClick()&quot;&gt;Save&lt;/button&gt;</pre><p>As shown in the example above, you place your target event name within parenthesis on the left of an equal sign and your event handler within quotes on the right of an equal sign. You can also bind an unlimited number of event handlers on the same event by separating them with a semi-colon:</p><pre>&lt;button (click)=&quot;handleClick1(); handleClick2(); …&quot;&gt;Save&lt;/button&gt;</pre><p>If you need access to the event payload object, you can pass $event as an argument to your handler function:</p><pre>&lt;button (click)=&quot;handleClick($event)&quot;&gt;Save&lt;/button&gt;</pre><p>Just like in the example above, make sure it’s passed exactly as &quot;$event”. Angular recognizes this and passes in the event payload that is the native event object emitted by the browser. If you pass it incorrectly (e.g.,<em> </em>missing the <strong>$</strong> sign), you will receive undefined in your handler function. If you need something specific from the payload object, you can pass it directly into the handler function with one of the event properties:</p><pre>&lt;button (click)=&quot;handleClick($event.target)&quot;&gt;Save&lt;/button&gt;</pre><p>There is another peculiar Angular event feature in relation to keyup and keydown events. If you only need to listen to specific keys, Angular offers shortcuts for that. For example, in order to listen to only the ENTER key, you can specify that key as a property of keyup or keydown events: keyup.enter or keydown.enter. These specific key events are called pseudo-events. You can use pseudo-events with event binding:</p><pre>&lt;input (keydown.enter)=&quot;onEnterKey($event)&quot;&gt;</pre><p>We can even listen to key combinations:</p><pre>&lt;input (keyup.control.shift.enter)=&quot;onCtrlShiftEnter($event)&quot;&gt;</pre><p>You can see how easy Angular makes it listen to complex key combinations. <a href="https://github.com/angular/angular/issues/18870">However, currently Angular lacks elaborate documentation on pseudo-events.</a> So I have written another brief blog post on <a href="https://medium.com/claritydesignsystem/angular-pseudo-events-d4e7f89247ee">Angular pseudo-events</a>.</p><p>Now, how about limitations in event binding? Well, there are some limitation is bound to a component template. This means you cannot listen to events fired outside the components template. Another limitation to event binding is that you cannot listen to events on your component’s host element, which wraps the component’s template. In the next post of this series, I will cover <strong>@HostListener </strong>which enables you to listen to events on the host itself.</p><p>But every rule has an exception. Even though you cannot listen to events outside of the component’s template, you can listen to events on global elements such as window, document, and body with event binding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*a1iM8LCG8MIkNnCOuFcU4Q.jpeg" /></figure><pre>&lt;button (document:click)=&quot;handleClick()&quot;&gt;Save&lt;/button&gt;</pre><p>In this example, the &quot;handleClick()&quot; function responds to clicks on both the button and on the entire document. However, listening to events on the global elements such as window or document is not recommended because it limits the reusability of the components themselves. If you have multiple instances of a component that handles one of the global<strong> </strong>events then all instances will simultaneously try to respond to the event after it is fired. This has a direct impact on the performance of your components and the application as a whole.</p><p>Something else a normal Angular event binding can handle are events that bubble up to a parent component from a child component. If a DOM event is fired in the child, the parent component will hear it as the event propagates up through. One thing to note is that only DOM events bubble up like this. Custom Angular events fired by the <a href="https://angular.io/api/core/EventEmitter">EventEmitter</a><strong> </strong>do not bubble up. Also, keep in mind that custom Angular events are different from custom DOM events, which bubble up just like regular DOM events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*WPV880vc61W5sKDyJ-IrZQ.jpeg" /></figure><p>Finally, the last thing to note about event binding is that you cannot dynamically add or remove the listener once event binding is set on an element in the component template. The bindings will be active once the element gets rendered into the DOM, and remain active until it’s removed from the DOM. This means, for event binding, it is Angular that controls when a listener starts or stops listening to their target events. Later in the series, we will look at using Renderer2 and RxJS to dynamically add and remove event listeners only if and when specific conditions are met. This will enable us to create components and directives that handle and manipulate events in complex ways.</p><h4><strong>Let’s Summarize It — Key Takeaways:</strong></h4><ul><li>Event binding is the simplest (or the most proper) way of listening to events in a component template.</li><li>With event binding, you cannot listen to events fired outside a component’s template with the exceptions of global elements such as window, document, and body.</li><li>Listening to global events in a reusable component is not recommended as it could potentially result in poor performance.</li><li>Parent component can hear and catch DOM events (not custom Angular events) fired inside child components as the events bubble up.</li><li>Event bindings will be active once they are set on an element and they will stay active until the elements are removed from the DOM so that means you cannot control when to add or remove event listeners dynamically.</li></ul><p>Stay tuned for the next blog posts on event listeners as I explore the other methods of listening to DOM events in Angular.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec7e9f51a1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-1-event-binding-3ec7e9f51a1d">Four ways of listening to DOM events in Angular (Part 1: Event Binding)</a> was originally published in <a href="https://medium.com/claritydesignsystem">Clarity Design System</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>