<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hassam Ali</title>
    <description>The latest articles on DEV Community by Hassam Ali (@hassam7).</description>
    <link>https://dev.to/hassam7</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F59742%2Fafc1c0c5-738d-4175-b1e7-2c830ea1f5b5.png</url>
      <title>DEV Community: Hassam Ali</title>
      <link>https://dev.to/hassam7</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hassam7"/>
    <language>en</language>
    <item>
      <title>React encapsulating data fetching logic with container components</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Sun, 05 Dec 2021 15:16:57 +0000</pubDate>
      <link>https://dev.to/hassam7/react-encapsulating-data-fetching-logic-with-container-components-20go</link>
      <guid>https://dev.to/hassam7/react-encapsulating-data-fetching-logic-with-container-components-20go</guid>
      <description>&lt;p&gt;Container components are components that encapsulate the data loading and data management for the child application.&lt;/p&gt;

&lt;p&gt;Let’s say you have a component called &lt;code&gt;StarShipInfo&lt;/code&gt; component which lists the information about starship&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const StarShipInfo = (id) =&amp;gt; {
 const [starShip, setStarShip] = useState(null);
 useEffect(() =&amp;gt; {
   const fetchStarShip = async () =&amp;gt; {
     const response = await fetch(`https://swapi.dev/api/starships/${id}/`);
     const data = await response.json();
     setStarShip(data);
   };
   fetchStarShip();
 }, [id]);
 return (
   starShip &amp;amp;&amp;amp; (
     &amp;lt;div&amp;gt;
       &amp;lt;p&amp;gt;Name: {starShip.name}&amp;lt;/p&amp;gt;
       &amp;lt;p&amp;gt;Hyper Drive Rating: {starShip.hyperdrive_rating}&amp;lt;/p&amp;gt;
       &amp;lt;p&amp;gt;Manufacturer: {starShip.manufacturer}&amp;lt;/p&amp;gt;
       &amp;lt;p&amp;gt;Class: {starShip.starship_class}&amp;lt;/p&amp;gt;
     &amp;lt;/div&amp;gt;
   )
 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By using container component pattern we can separate out the data fetching logic into a separate container.&lt;br&gt;
First, let’s create a separate component called &lt;code&gt;StarShipInfoLoader&lt;/code&gt;. The purpose of this component is to create a fetch request, wait for the request to be completed, and then render the &lt;code&gt;StarShipInfo&lt;/code&gt; component. The &lt;code&gt;StarShipInfo&lt;/code&gt; component is passed as a children prop to this component, we access the passed component and render it with data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const StarShipInfoLoader = ({ id, children }) =&amp;gt; {
 const [starShip, setStarShip] = useState(null);
 useEffect(() =&amp;gt; {
   const fetchStarShip = async () =&amp;gt; {
     const response = await fetch(`https://swapi.dev/api/starships/${id}/`);
     const data = await response.json();
     setStarShip(data);
   };
   fetchStarShip();
 }, [id]);
 return (
   &amp;lt;&amp;gt;
     {starShip &amp;amp;&amp;amp;
       Children.map(children, (child) =&amp;gt; {
         if (isValidElement(child)) {
           return cloneElement(child, { starShip });
         }
       })}
   &amp;lt;/&amp;gt;
 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is how we can use the &lt;code&gt;StarShipInfoLoader&lt;/code&gt; and &lt;code&gt;StarShipInfo&lt;/code&gt; together.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;StarShipInfoLoader id={id}&amp;gt;
   &amp;lt;StarShipInfo /&amp;gt;
 &amp;lt;/StarShipInfoLoader&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>react</category>
      <category>javascript</category>
      <category>statemanagement</category>
      <category>datafetching</category>
    </item>
    <item>
      <title>How to create your own getEelmentById</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Mon, 05 Jul 2021 19:05:39 +0000</pubDate>
      <link>https://dev.to/hassam7/create-your-own-geteelmentbyid-3fdm</link>
      <guid>https://dev.to/hassam7/create-your-own-geteelmentbyid-3fdm</guid>
      <description>&lt;p&gt;In this write up I am going to show how to create your getElementById function it will be similar to &lt;code&gt;document.getElementById&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So before we begin I want to clarify what &lt;code&gt;document.getElementById&lt;/code&gt; does it. It is a function when called with a given id finds the DOM element which has same id as the one passed to the function. If there are multiple ids it then will return the first element. Before we begin writing our function let's quickly recap how DOM is structured and what are some useful methods which we can use.&lt;/p&gt;

&lt;h2&gt;
  
  
  DOM
&lt;/h2&gt;

&lt;p&gt;In layman terms DOM stands for document object model it is a tree like representation of HTML element. so for example lets say we have following HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE HTML&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Hello World&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1&amp;gt; A quick brown fox jumps over the lazy dog &amp;lt;/h1&amp;gt;
  &amp;lt;div&amp;gt;
    &amp;lt;h2&amp;gt;This is a h2&amp;lt;/h2&amp;gt;
    &amp;lt;p&amp;gt;This is a paragraph&amp;lt;/p&amp;gt;
    &amp;lt;article&amp;gt;This is a article&amp;lt;/article&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For this HTML the DOM would be like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zK6FTJkT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10nimj6psiu4ejf947lq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zK6FTJkT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10nimj6psiu4ejf947lq.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
In the above image we can see all the DOM nodes for the HTML. There are different types of DOM nodes. You can see the list at &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType"&gt;MDN&lt;/a&gt;. The &lt;code&gt;document.getElementId&lt;/code&gt; works on HTML element and HTML elements have &lt;code&gt;nodeType&lt;/code&gt; of 1. &lt;/p&gt;

&lt;p&gt;So first of all we need to get all the children of &lt;code&gt;document.body&lt;/code&gt; we can do this by calling &lt;code&gt;document.body.children&lt;/code&gt;, this method return &lt;code&gt;HTMLCollection&lt;/code&gt; so we need to convert it into array now there are different ways via which we can do that but the simples one is simply used the spread operator eg &lt;code&gt;[...root.children]&lt;/code&gt;. Now this array contains all the children of &lt;code&gt;document.body&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Now we will iterate over array and during each iteration we will pick an item from the array and we will check if the id of the elements is equal to the id we are looking for, this can done by calling &lt;code&gt;.id&lt;/code&gt; on the selected item. if &lt;code&gt;id&lt;/code&gt; matches then we will return the item otherwise we will repeat the same process on all of the children of the current element. In computer science this type of algorithm is called Depth First Search.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const walkDOM = (root, elementId) =&amp;gt; {
 let result = null;
 const elements = [...root.children];
 for (let element of elements) {
  if (element.id === elementId) return element;
  if (element.children.length &amp;amp;&amp;amp; element.nodeType === 1) {
   result = walkDOM(element, elementId);
   if (result) return result;
  }
 }
 return result;
};
const getElementById = (elementId) =&amp;gt; {
 return walkDOM(document.body, elementId);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that this is not a replacement for &lt;code&gt;document.getElementById&lt;/code&gt; but a simple snippet showing how powerful and feature rich the DOM the API is and how far we can go in web development without knowing how these methods work.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>dom</category>
      <category>algorithms</category>
      <category>dfs</category>
    </item>
    <item>
      <title>TypeScript: Typeguards and Type Narrowing.</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Sun, 27 Jun 2021 21:22:43 +0000</pubDate>
      <link>https://dev.to/hassam7/typescript-typeguards-and-type-narrowing-2cof</link>
      <guid>https://dev.to/hassam7/typescript-typeguards-and-type-narrowing-2cof</guid>
      <description>&lt;p&gt;Hi, &lt;br&gt;
In this post we will be exploring a feature of TypeScript called type guards. To be more precise we will be exploring the typeguard using the &lt;code&gt;in&lt;/code&gt; operator. &lt;/p&gt;

&lt;p&gt;Note: The &lt;code&gt;in&lt;/code&gt; operator is javascript feature not TypeScript.&lt;/p&gt;

&lt;p&gt;Consider the following scenario: I am writing a todo application. In my todo application I have two types of Todos:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Anonymous Todo&lt;/li&gt;
&lt;li&gt;Validated Todo&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;Anonymous&lt;/code&gt; todo have text and id fields. Lets write an interface for it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface AnonymousTodo {
    text: string;
    id: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Validated&lt;/code&gt; Todo is similar to anonymous todo but with two extra fields &lt;code&gt;authorName&lt;/code&gt; and &lt;code&gt;validationDate&lt;/code&gt;. Lets write interface for it too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ValidatedTodo {
    text: string;
    id: number;
    authorName: string;
    validationDate: Date;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so far so good, now lets write a method which will print the todo to console. So if anonymous todo is passed we should prepend anonymous logging text and id, but if ValidatedTodo is passed we should prepend 🔒 before logging the todo details.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function printValidation(todo: AnonymousTodo | ValidatedTodo) {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so our function &lt;code&gt;printValidation&lt;/code&gt; accepts both &lt;code&gt;AnonymousTodo&lt;/code&gt; and &lt;code&gt;ValidatedTodo&lt;/code&gt;. But if you try to &lt;code&gt;console.log(log.authorName)&lt;/code&gt;; you will get the following error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Property 'authorName' does not exist on type 'ValidatedTodo | AnonymousTodo'.
  Property 'authorName' does not exist on type 'AnonymousTodo'.(2339)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets try to log &lt;code&gt;id&lt;/code&gt; instead of &lt;code&gt;authorName&lt;/code&gt;, that works fine. Now lets try to log &lt;code&gt;text&lt;/code&gt;, yes thats also works fine finally lets try to log &lt;code&gt;validationDate&lt;/code&gt;. we get similar error as before.&lt;/p&gt;

&lt;p&gt;So why is that? This is because TypeScript wants to make sure we only access the properties which are available on both &lt;code&gt;ValidatedTodo&lt;/code&gt; and &lt;code&gt;AnonymousTodo&lt;/code&gt;, in our case these common properties are &lt;code&gt;id&lt;/code&gt; and &lt;code&gt;text&lt;/code&gt;. But we want to access &lt;code&gt;authorName&lt;/code&gt; and &lt;code&gt;validationDate&lt;/code&gt; too. How can we do that? &lt;/p&gt;

&lt;p&gt;This is where Typeguard comes in. We can use the typeguard to narrow the type. So as of now &lt;code&gt;todo&lt;/code&gt; can be one of the two types. It can be either of type &lt;code&gt;AnonymousTodo&lt;/code&gt; or &lt;code&gt;ValidatedTodo&lt;/code&gt;. So we need to narrow it down for TypeScript, so TypeScript will know which type it is and will allow to access the properties available on it instead of allowing us to only access common properties. If it does not make sense do not worry. I have example coming up. Hopefully it will clear things up&lt;/p&gt;

&lt;p&gt;There are multiple different type of guards available eg: &lt;code&gt;instanceof&lt;/code&gt;,&lt;code&gt;typeof&lt;/code&gt; etc. But in our case as we are using interface we will narrow the type using the &lt;code&gt;in&lt;/code&gt; operator. The &lt;code&gt;in&lt;/code&gt; operator is javascript language feature which can be used to check if a property is present in an object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myObj = {apple: 20};
if ("apple" in myObj) console.log(`We have ${myObj.apple} apples`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in the above snippet property &lt;code&gt;apple&lt;/code&gt; is present in the &lt;code&gt;myObj&lt;/code&gt; so we get true and a message will be logged to console. so lets integrate this in our example. Before we do that lets create objects of both type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const todoWithValidation: ValidatedTodo = { text: "Ping", id: 1, validationDate: new Date(), authorName: "admin" };
const todoWithoutValidation: AnonymousTodo = { text: "Pong", id: 1 };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By looking at the both object we can see that &lt;code&gt;ValidatedTodo&lt;/code&gt; will always have &lt;code&gt;validationDate&lt;/code&gt; and &lt;code&gt;authorName&lt;/code&gt;. So we can tell TypeScript to all at these two properties to distinguish between the &lt;code&gt;ValidatedTodo&lt;/code&gt; and &lt;code&gt;AnonymousTodo&lt;/code&gt; and we can do that by adding a simple &lt;code&gt;if&lt;/code&gt; check which checks for these properties using the &lt;code&gt;in&lt;/code&gt; operator. lets write the code for this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function printValidation(todo: AnonymousTodo | ValidatedTodo) {
    if ("authorName" in todo &amp;amp;&amp;amp; "validationDate" in todo) {
        console.log(`🔒 ${todo.authorName}, ${todo.validationDate}, ${todo.text}`);
    } else {
        console.log(`Anonymous ${todo.id}, ${todo.text}`);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the else block you can only access the properties of &lt;code&gt;AnonymousTodo&lt;/code&gt; and inside the &lt;code&gt;if&lt;/code&gt; block you can only access the properties of &lt;code&gt;ValidatedTodo&lt;/code&gt; and outside of these scope you can only access the common properties.&lt;/p&gt;

&lt;p&gt;Bonus:&lt;br&gt;
Instead of the &lt;code&gt;if ("authorName" in todo &amp;amp;&amp;amp; "validationDate" in todo)&lt;/code&gt; we can also use a type predicate function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isValidatedTodo(todo: AnonymousTodo | ValidatedTodo): todo is ValidatedTodo {
  return ("authorName" in todo &amp;amp;&amp;amp; "validationDate" in todo);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the return type type of the function. You can find more details on type predicate in the official docs. Thats all for now. If you want to play with code you can access it &lt;a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGpwDbACZ0tgFQHtsjkBvAKGRuUgA8wAuZAZzClAHMBua2nCxABXALYAjaH1rI4wsAAsiUAHJxREFu04he-GgDdMOPMCIgAInk3IrkPgF9KlUJFiIUAQRDmAnqKJhVmJSCn06CEYtDm5pAWwhMUkoR2cYYRAEMDMQZGBWdCxcfBCiAAowEiIWbz8AoNLkAB80Y2KIQiqAShZK0PzWoutO0KoaKAgwYShcsoAiOUVlNQ05vNy+sgAyLeQ5oyHs8zsINdA6btTKdMyj3IAHHTBCkzuyjCIuGp8Qf0DgqrNQavDqlLphGTAGDIeaLJSqdSndbID5cZA7PYHV45E5nXKo8FjGS0BDmVhEDAQAB0qLKAANALwbgCRd5AAEnIqKpcOWiIcABo2RzPlSscUcdZ+YLOQwwA46V04jQHMgIBhWCgicTkKSQOTKTTPvTar96qwpcKcJL2dLIrL5YrkE4nJQdewLqQAOrARQvMXmFi+4aNAC8FAiUT2AAVuHMBYJkABGAWi0zHaxCCAAd1s1jKXQF3IRGhYC2wolAawcfFdYHdRC9S3kgbu3zq-xDYZlJejuljeQSicdfEoj1czZyFSqDYU4-MCpHT1nIEnnu9SibbVTIHnQA"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Composition vs Inheritance</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Sat, 26 Jun 2021 12:14:42 +0000</pubDate>
      <link>https://dev.to/hassam7/composition-vs-inheritance-4oo2</link>
      <guid>https://dev.to/hassam7/composition-vs-inheritance-4oo2</guid>
      <description>&lt;p&gt;I recently completed an online course and these are my takeaway from Composition and Inheritance.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inheritance
&lt;/h2&gt;

&lt;p&gt;With inheritance we can extend the functionality of an existing class by overriding its method in a Child class e.g&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Parent {
  function sayHi() {
    console.log("sayHi from Parent");
  }
}
class Child {
  function sayHi() {
    console.log("sayHi from the Child");
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inheritance is characterised by an "is-a" relationship between two classes e.g Apple is Fruit, Car is a Vehicle etc. Inheritance is suited for use cases where there is tight coupling between the classes which is rarely the case in the real world.&lt;/p&gt;

&lt;p&gt;Lets say your are building a house and you need to model a window in code. So you might come up with following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Window {
  height: number;
  width: number;
  open: boolean;
  toggleOpen() {}
  area(){}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The properties are self explanatory. Pay attention to the &lt;code&gt;area&lt;/code&gt; method. It calculates the area.&lt;br&gt;
Now in addition to window we also want to add a &lt;code&gt;Wall&lt;/code&gt;. The code for the wall might look as follow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Wall {
  height: number;
  width: number;
  color: string;
  area() {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You see that they share some common properties so you use inheritance for code reuse. You come up with class named &lt;code&gt;Rectangle&lt;/code&gt; which has common properties from the both of the classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Rectangle {
  height: number;
  width: number;
  area() {}
}

class Wall extends Rectangle {
  color: string;
}

class Window extends Rectangle {
  open: boolean;
  toggleOpen() {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So according to this code &lt;code&gt;Wall&lt;/code&gt; is rectangle and &lt;code&gt;Window&lt;/code&gt; is also a rectangle, now let's suppose the we want to introduce new type of window called circle window. &lt;/p&gt;

&lt;p&gt;Circle window can not extend from &lt;code&gt;Rectangle&lt;/code&gt; window because it does not make sense. Now this is a type of Window so you might be tempted to inherit from the window class but window class itself inherits from &lt;code&gt;Rectangle&lt;/code&gt; so although it can be extended but it will also inherit the methods from &lt;code&gt;Rectangle&lt;/code&gt; class which does not make sense and it as it is derived from &lt;code&gt;Rectangle&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You wanted a banana but what you got was a gorilla holding the banana -- Joe Armstrong&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So an other way is be to create a new Circle class and extend from it. It might seem a nice idea initially but as the application grows we might encounter again a similar situation. I will show on later how we can resolve this via composition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Circle {
 radius: number;
 area(){}
}

class CircleWindow extends Circle {
  open: boolean;
  toggleOpen() {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Composition
&lt;/h2&gt;

&lt;p&gt;For this I would quote the following text from GoF Design Patterns Book&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. [...]  Object composition is defined dynamically at run-time through objects acquiring references to other objects&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To recap, composition is an alternative strategy to class Inheritance for code reuse. In composition a class will have reference to another class instance as its memeber variable. Lets see this with an example. I will change the example in the last section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Shape {
 area(): number;
}

class Wall {
  color: string;
  area(){}
  dimensions: Shape;
}

class Window {
  open: boolean;
  toggleOpen(){}
  area(){}
  dimensions: Shape;
}
class Rectangle implements Shape {
  height;
  width;
  area(){}
}
class Circle implements Shape {
  radius;
  area(){}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in this example inside  &lt;code&gt;Wall&lt;/code&gt; and &lt;code&gt;Window&lt;/code&gt; we have a member variable called dimensions, which is of type Shape. The interface &lt;code&gt;Shape&lt;/code&gt; guarantees us that their will be always a method named &lt;code&gt;area&lt;/code&gt; present. So now we both &lt;code&gt;Window&lt;/code&gt; and &lt;code&gt;Wall&lt;/code&gt; can accept any object for its memember variable dimensions as long it satisfies the interface &lt;code&gt;Shape&lt;/code&gt;, in a way we have delegated the responsibility for calculating the area to the class &lt;code&gt;Rectangle&lt;/code&gt; and &lt;code&gt;Circle&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Inheritance vs Composition
&lt;/h2&gt;

&lt;p&gt;So this was a quick recap of inheritance vs composition. This is very difficult to explain topics but with time you develop instincts for this. Now lets take a look at &lt;code&gt;Abstract&lt;/code&gt; class and &lt;code&gt;Interface&lt;/code&gt;. These are features provided by programming languages to aid in inheritance and composition.&lt;/p&gt;

&lt;h2&gt;
  
  
  Abstract Class
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Abstract&lt;/code&gt; classes are classes for which you create an instance of them. They maybe used to provide a default implementation in case the overriding classes does not provide one. In javacript you can create an abstract class by adding the keyword &lt;code&gt;abstract&lt;/code&gt; infront of the class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class Destroyer {
  onDestroy() {
    db.close();
    analytics.send("Database Closed);
  }
}
class MyDestroyer extends Destroyer {
}
The class MyDestroyer gets the implemntation defined in class Destroyer.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Interface
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Interface&lt;/code&gt; are used to define set of properties that must exist on class. Interface only contains what a class implentating that interface should have it does not dictate what it should do. Interface are loosely coupled compared to Abstract classes and are usually favoured.&lt;/p&gt;

&lt;p&gt;In next part of the article I will show an example of inheritance and how to convert it into composition along with use of &lt;code&gt;abstract&lt;/code&gt; and &lt;code&gt;interface&lt;/code&gt;. stay tuned!🙂 &lt;/p&gt;

&lt;p&gt;P.S: if you find any mistakes please let me know in comments. Design Patterns are difficult to understand and even harder to write about.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Exploring ViewChild Selectors</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Mon, 27 Jul 2020 19:16:32 +0000</pubDate>
      <link>https://dev.to/hassam7/exploring-viewchild-selectors-4182</link>
      <guid>https://dev.to/hassam7/exploring-viewchild-selectors-4182</guid>
      <description>&lt;h1&gt;
  
  
  &lt;code&gt;ViewChild&lt;/code&gt;
&lt;/h1&gt;

&lt;p&gt;&lt;code&gt;ViewChild&lt;/code&gt; decorator is most commonly used to access the Child Component's instance and template. This is one the most common use cases. In this article we will be exploring several lesser known use cases.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;ViewChild&lt;/code&gt; Selectors
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;ViewChild&lt;/code&gt; has following selectors&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Any class with the @Component or @Directive decorator&lt;/li&gt;
&lt;li&gt;A template reference variable as a string (e.g. query  with @ViewChild('cmp'))&lt;/li&gt;
&lt;li&gt;Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)&lt;/li&gt;
&lt;li&gt;Any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)&lt;/li&gt;
&lt;li&gt;A TemplateRef (e.g. query  with @ViewChild(TemplateRef) template;)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The 1, 2 and 5 are most commonly known and used. In this write up I will be exploring 3 and 4. So let's get started!&lt;/p&gt;

&lt;h2&gt;
  
  
  Accessing Child Component Provider Without Injecting.
&lt;/h2&gt;

&lt;p&gt;Suppose you have a component called Parent component inside which there is another component called child. Child Component injects a service inside it called &lt;code&gt;RandomNumberService&lt;/code&gt; which has method called &lt;code&gt;getRandomNumber&lt;/code&gt; this method return a random number. This service is provided in Child's components decorator metadata&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  providers: [RandomNumberService],
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Service injected via this method is not singleton. For each instance of child component a new instance &lt;code&gt;RandomNumberService&lt;/code&gt; will created. So if we want to access this service we will need to use &lt;code&gt;ViewChild&lt;/code&gt;, lets see how we can use it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class ParentComponent implements OnInit {
  @ViewChild(RandomNumberService) randomNumberService: RandomNumberService;
  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    console.log(this.randomNumberService.number);
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can achieve the same result by accessing the child component's instance and then accessing the service but then we would have to make sure that the service instance variable is public otherwise it won't work so to avoid that we can use &lt;code&gt;ViewChild&lt;/code&gt; with service.&lt;/p&gt;

&lt;p&gt;Now lets take at point 4 which is &lt;/p&gt;

&lt;h2&gt;
  
  
  Accessing Any Provider Defined Through A String Token.
&lt;/h2&gt;

&lt;p&gt;Moving forward with previous example suppose that inside child component you have provider defined in following way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  providers: [{provide: 'TokenName', useValue: 'Foo Bar'}],
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and now you need to access it. You can use the following format of &lt;code&gt;ViewChild&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class ParentComponent implements OnInit {
  @ViewChild('TokenName') token: RandomNumberService;
  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    console.log(this.token); // logs 'Foo Bar'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thats all for now!. Let me know how you use angular decorators and what are your favourite tips and tricks, and do let me know if missed anything.&lt;/p&gt;

&lt;p&gt;Thanks for reading! &lt;br&gt;
&lt;em&gt;cover image credits: &lt;a href="https://unsplash.com/photos/1seONCyPWfQ"&gt;https://unsplash.com/photos/1seONCyPWfQ&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>angulartips</category>
      <category>decorators</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Disable Interpolation Angular</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Mon, 27 Jul 2020 09:24:20 +0000</pubDate>
      <link>https://dev.to/hassam7/disable-string-interpolation-1i18</link>
      <guid>https://dev.to/hassam7/disable-string-interpolation-1i18</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fe3ulfv8d79gm6vhuwjii.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fe3ulfv8d79gm6vhuwjii.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
You can disable string interpolation in angular by using &lt;code&gt;ngNonBindable&lt;/code&gt; directive. This is useful in cases where you want to show some text but do not want it to be interpolated like showing some code snippet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;

In angular pair of curly braces are used for string interpolation e.g

&amp;lt;span ngNonBindable&amp;gt;My name is {{name}}&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;{{ 1 + 1 }}&amp;lt;/div&amp;gt; // &amp;lt;div&amp;gt;2&amp;lt;/div&amp;gt;
&amp;lt;div ngNonBindable&amp;gt;{{ 1 + 1 }}&amp;lt;/div&amp;gt; // &amp;lt;div&amp;gt;{{1 + 1}}&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>angular</category>
      <category>typescript</category>
      <category>angulartips</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Angular CDK Virtual Scroll</title>
      <dc:creator>Hassam Ali</dc:creator>
      <pubDate>Sat, 27 Jul 2019 09:26:39 +0000</pubDate>
      <link>https://dev.to/hassam7/angular-cdk-virtual-scroll-4ldj</link>
      <guid>https://dev.to/hassam7/angular-cdk-virtual-scroll-4ldj</guid>
      <description>&lt;h1&gt;
  
  
  What is Virtual Scrolling?
&lt;/h1&gt;

&lt;p&gt;Modern web application are complex. They have a lot of moving parts, complexity and often times they have to deal with huge amount of data.&lt;/p&gt;

&lt;p&gt;Consider that you have application in which you have to display a list of users, a very common use case.&lt;/p&gt;

&lt;p&gt;As the number of items in the list increase so does number of elements in DOM resulting in more memory and cpu usage. &lt;br&gt;
We can reduce memory and cpu consumption by rendering only limited set of all the items, we can determine this limited set by looking at the height of container, scroll position and height of individual item and then perform some calculations which tell us which items from the list should rendered in DOM and as soon user scroll we again perform this calculation, remove previously rendered items and render new items according to calculation. All of this sounds very complex and it is, but the good news is that Angular Material CDK Virtual Scroll does this all for you and then some more. From now on I will be referring Angular Material CDK Virtual Scroll as Virtual Scroll&lt;/p&gt;

&lt;p&gt;So let's get started!  &lt;/p&gt;

&lt;h1&gt;
  
  
  Prerequisites
&lt;/h1&gt;

&lt;p&gt;Before we begin we need a sample application with list of data so we can play with it and later on add angular virtual scroll to it. I have created a &lt;a href="https://stackblitz.com/edit/ngfor-faker" rel="noopener noreferrer"&gt;small example&lt;/a&gt;&lt;br&gt;
This example is built on using Angular version 8. It uses fake to generate fake data, add it to array and uses &lt;code&gt;*ngFor&lt;/code&gt; to render item of array as DOM elements in template. &lt;/p&gt;

&lt;h1&gt;
  
  
  Installation
&lt;/h1&gt;

&lt;p&gt;Installing Material CDK is pretty straight forward. If you are following along: In the stackblitz demo click on dependencies, it is just beneath window where project file are listed see screen shot below, type &lt;code&gt;@angular/cdk&lt;/code&gt; and hit enter this will install material cdk. If you want to install it inside your angular cli project simply type &lt;code&gt;npm i --save @angular/cdk&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnftcfkc96t4wfcy7jfej.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnftcfkc96t4wfcy7jfej.png" alt="Installing CDK"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you have installed CDK, we are ready to move towards next step: using it!&lt;/p&gt;

&lt;h1&gt;
  
  
  Usage
&lt;/h1&gt;

&lt;p&gt;Before we can begin using the Virtual Scroll we need to import the module for it. Let's import it. Open your &lt;code&gt;app.module.ts&lt;/code&gt; add this line after the last import&lt;/p&gt;

&lt;p&gt;&lt;code&gt;import  {  ScrollingModule  }  from  '@angular/cdk/scrolling';&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will import the &lt;code&gt;ScrollingModule&lt;/code&gt;, now we need to tell our &lt;code&gt;app.module.ts&lt;/code&gt; to import contents of this module. For this inside the imports array add &lt;code&gt;ScrollingModule&lt;/code&gt; your &lt;code&gt;app.module.ts&lt;/code&gt; will look like this&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 import  {  NgModule  }  from  '@angular/core';
import  {  BrowserModule  }  from  '@angular/platform-browser';
import  {  FormsModule  }  from  '@angular/forms';
import  {  AppComponent  }  from  './app.component';
import  {  ScrollingModule  }  from  '@angular/cdk/scrolling';

@NgModule({
imports:  [  BrowserModule,  FormsModule,  ScrollingModule  ],
declarations:  [  AppComponent  ],
bootstrap:  [  AppComponent  ]
})
export  class  AppModule  {  }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we are ready to use Virtual Scroll!&lt;/p&gt;

&lt;p&gt;We will modify our application to use Virtual Scroll! Here is link to &lt;a href="https://stackblitz.com/edit/ngfor-faker-material-cdk?file=src/app/app.component.html" rel="noopener noreferrer"&gt;stackblitz app&lt;/a&gt; with desired state. This is same as our initial app but with Angular CDK installed and imported. &lt;/p&gt;

&lt;p&gt;Open &lt;code&gt;app.component.ts&lt;/code&gt;, inside the constructor of &lt;code&gt;AppComponent&lt;/code&gt; you will see&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

constructor()  {
  this.persons =  Array(100).fill(0).map(()  =&amp;gt;  { 
  return {
      name: faker.name.findName(),
      bio: faker.hacker.phrase(),
      avatar: faker.image.business()
    }
  })
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What this does is creates an array of 100 objects, each object contains name, bio and avatar generated by &lt;code&gt;faker&lt;/code&gt;. This array is assigned to instance variable called &lt;code&gt;persons&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now open the template file for this component (&lt;code&gt;app.component.html&lt;/code&gt;).&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;div  class="search-wrapper cf"&amp;gt;
  &amp;lt;input  type="text"&amp;gt;
  &amp;lt;button (click)="undefined"&amp;gt;Go To&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div *ngFor="let person of persons;let i = index"&amp;gt;
  &amp;lt;div class="card"&amp;gt;
      &amp;lt;img  src="https://i.imgur.com/63S0RAq.png"  alt="Avatar"&amp;gt;
      &amp;lt;div  class="container"&amp;gt;
        &amp;lt;h4&amp;gt;&amp;lt;b&amp;gt;{{person.name}}&amp;lt;/b&amp;gt;&amp;lt;/h4&amp;gt;
        &amp;lt;h4&amp;gt;&amp;lt;b&amp;gt;ID: {{i}}&amp;lt;/b&amp;gt;&amp;lt;/h4&amp;gt;
        &amp;lt;p&amp;gt;{{person.bio.substr(0, 30)}}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The template consist of a button with click handler defined as of now it does nothing. Below the button we are using &lt;code&gt;*ngFor&lt;/code&gt; to iterate over person array, for each person array we create a div with class card. This &lt;code&gt;card&lt;/code&gt; div consist person's name, id, bio and avatar. We are displaying only first 30 characters of bio.&lt;/p&gt;

&lt;p&gt;Now let's modify our template to use Virtual Scroll. For this first we need to wrap our ngFor with &lt;code&gt;&amp;lt;cdk-virtual-scroll-viewport&amp;gt;&lt;/code&gt; and then replace &lt;code&gt;*ngFor&lt;/code&gt;with . &lt;code&gt;cdk-virtual-scroll-viewport&lt;/code&gt; has a required input called &lt;code&gt;[itemSize]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;itemSize&lt;/code&gt; represents the height of item in pixels which we are rendering in our case this should be exact height of our card div which is &lt;code&gt;141px&lt;/code&gt;. Another thing to note is that height of all of our cards component should be same. As of now the Virtual Scroll does not support fully support variable height. We will look into matter of variables heights later.&lt;/p&gt;

&lt;p&gt;so lets wrap our &lt;code&gt;*ngFor&lt;/code&gt; with &lt;code&gt;cdk-virtual-scroll-viewport&lt;/code&gt; and replace our &lt;code&gt;*ngFor&lt;/code&gt;with &lt;code&gt;*cdkVirtualFor&lt;/code&gt;. Another thing which needs to be done before we see any visual change is giving height to our &lt;code&gt;cdk-virtual-scroll-viewport&lt;/code&gt; I want to show two user cards at once so I will give &lt;code&gt;cdk-virtual-scroll-viewport&lt;/code&gt; height of &lt;code&gt;282px&lt;/code&gt; &lt;em&gt;(size of single card is 141, 141 * 2 = 282)&lt;/em&gt; you can either give height in stylesheet our add style tag. I will be adding height via style tag &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;cdk-virtual-scroll-viewport [itemSize]="141" style="height: 282px"&amp;gt;
&amp;lt;div *cdkVirtualFor="let person of persons;let i = index"&amp;gt;
  &amp;lt;div  class="card"&amp;gt;
    &amp;lt;img  src="https://i.imgur.com/63S0RAq.png"  alt="Avatar"&amp;gt;
    &amp;lt;div  class="container"&amp;gt;
        &amp;lt;h4&amp;gt;&amp;lt;b&amp;gt;{{person.name}}&amp;lt;/b&amp;gt;&amp;lt;/h4&amp;gt;
        &amp;lt;h4&amp;gt;&amp;lt;b&amp;gt;ID: {{i}}&amp;lt;/b&amp;gt;&amp;lt;/h4&amp;gt;
        &amp;lt;p&amp;gt;{{person.bio.substr(0, 30)}}...&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;/div&amp;gt;
&amp;lt;/cdk-virtual-scroll-viewport&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we can see that our user list items are rendered. Lets verify that we DOM items are created dynamically and reused. Open your browser developers tools, select &lt;code&gt;Elements Panel&lt;/code&gt;. Find the DOM element shown in screen shot below and expand it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc01ao2poi79qhhuo6yu0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc01ao2poi79qhhuo6yu0.png" alt="Virtual Scroll in dev tools"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now if you scroll through the list you will see that limited number of DOM elements are created, which leads to reduce memory and cpu usage.&lt;/p&gt;

&lt;h1&gt;
  
  
  Items with variable heights
&lt;/h1&gt;

&lt;p&gt;As of now Virtual Scroll does not support variable heights, but it is being worked on and is in experimental phase which means you should not use it in production as its api may change. &lt;/p&gt;

&lt;p&gt;For items with variable height we need to install &lt;code&gt;@angular/cdk-experimental&lt;/code&gt;. You can install into stackblitz by click on dependencies and type &lt;code&gt;@angular/cdk-experimental&lt;/code&gt;and hit enter. It will install the experimental cdk for you. User of angular cli can install it by &lt;code&gt;npm @angular/cdk-experimental&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now we need to import it into our app module. Just like before, add following line in &lt;code&gt;app.module.ts&lt;/code&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import  {  ScrollingModule  as  ExperimentalScrollingModule}  from  '@angular/cdk-experimental/scrolling';

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It will import &lt;code&gt;ScrollingModule&lt;/code&gt; and rename it as &lt;code&gt;ExperimentalScrollingModule&lt;/code&gt;. We need both &lt;code&gt;ScrollingModule&lt;/code&gt; and &lt;code&gt;ExperimentalScrollingModule&lt;/code&gt; for variable height to work. Now add &lt;code&gt;ExperimentalScrollingModule&lt;/code&gt; into import array. You &lt;code&gt;app.module.ts&lt;/code&gt; should look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
  {  NgModule  }  from  '@angular/core';
import  {  BrowserModule  }  from  '@angular/platform-browser';
import  {  FormsModule  }  from  '@angular/forms';
import  {  AppComponent  }  from  './app.component';
import  {  ScrollingModule  }  from  '@angular/cdk/scrolling';
import  {  ScrollingModule  as  ExperimentalScrollingModule}  from  '@angular/cdk-experimental/scrolling';

@NgModule({
imports:  [  BrowserModule,  FormsModule,  ScrollingModule,  ExperimentalScrollingModule  ],
declarations:  [  AppComponent  ],
bootstrap:  [  AppComponent  ]
})
export  class  AppModule  {  }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now open &lt;code&gt;app.component.html&lt;/code&gt; and replace &lt;code&gt;[itemSize]&lt;/code&gt; with &lt;code&gt;autosize&lt;/code&gt;. Thats it! Now you can elements of variable height in your Virtual Scroll but as said before this feature is experimental and should not be used. You can find example for autosize &lt;a href="https://stackblitz.com/edit/cdk-virtual-scroll-autosize?file=src/app/app.module.ts" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>cdk</category>
      <category>virtualscroll</category>
      <category>material</category>
    </item>
  </channel>
</rss>
