<?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[Design Pattern — Iterator in Angular - Medium]]></title>
        <description><![CDATA[Design Pattern — Iterator in Angular - Medium]]></description>
        <link>https://medium.com/design-patterns-iterator-in-angular?source=rss----1f20fcb4bc95---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Design Pattern — Iterator in Angular - Medium</title>
            <link>https://medium.com/design-patterns-iterator-in-angular?source=rss----1f20fcb4bc95---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 13 Nov 2026 02:27:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/design-patterns-iterator-in-angular" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design Pattern — Iterator in Angular]]></title>
            <link>https://medium.com/design-patterns-iterator-in-angular/design-patterns-iterator-in-angular-9508f3b69d08?source=rss----1f20fcb4bc95---4</link>
            <guid isPermaLink="false">https://medium.com/p/9508f3b69d08</guid>
            <category><![CDATA[iterator-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[Bulicka Ola]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 01:35:01 GMT</pubDate>
            <atom:updated>2025-04-01T19:50:46.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern — Iterator in Angular</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UbbgOJeAnXM1uMYSRgMDQ.png" /><figcaption>Image generated by Copilot AI</figcaption></figure><p><strong>Behavioral patterns</strong> are design patterns that deal with the ways objects communicate with each other.</p><p>Behavioral patterns consist of:</p><p>1. <a href="https://medium.com/design-patterns-chain-of-responsibility-in-angular/design-patterns-chain-of-responsibility-in-angular-5bd0b10b011d">Chain of Responsibility</a><br>2. Command<br>3. Interpreter<br>4. Iterator<br>5. Mediator<br>6. <a href="https://medium.com/design-patterns-memento-in-angular/design-patterns-memento-in-angular-a4d8985f4771">Memento</a><br>7. <a href="https://medium.com/design-patterns-observer-in-angular/behavioral-patterns-are-design-patterns-that-deal-with-the-ways-objects-communicate-with-each-other-2b4ff0cba9e5">Observer</a><br>8. State<br>9. Strategy<br>10. Template Method</p><p>In this article, I will explain how the<strong> Iterator </strong>pattern works. You can see and run an example of the <strong>Iterator </strong>pattern in a demo project, which can be found at this link <a href="https://stackblitz.com/~/github.com/KasiaKasia/DESIGN-PATTERNS"><strong>here</strong></a>.</p><p>As the name suggests, the <strong>Iterator </strong>design pattern traverses through a given set of data in a specific manner without requiring knowledge of the internal representation of the data. These sets can be arrays, collections, lists, stacks, trees, etc. The core idea of the <strong>Iterator </strong>design pattern is to define the behavior of traversing a collection in a separate object called an Iterator.</p><p>In my opinion, the <strong>Iterator </strong>design pattern is primarily used for traversing binary trees and graphs. Using loops in such cases would be unclear, but an <strong>Iterator </strong>can handle these structures through custom methods, often called next(). It separates the logic of iteration from the data structure itself.</p><p>In the case of complex structures, iterators make the code more readable and easier to maintain. Therefore, to illustrate the <strong>Iterator </strong>design pattern, I will propose an implementation of a binary tree. The Tree class will contain a root field of type TreeNode, to which elements of the tree will be added. The add function in the Tree class adds a new node to the tree. Below is the implementation of the TreeNode and Tree class:</p><pre>class TreeNode {<br>  value: string;<br>  left: TreeNode | null;<br>  right: TreeNode | null;<br><br>  constructor(value: string, left: TreeNode | null = null, right: TreeNode | null = null) {<br>    this.value = value;<br>    this.left = left;<br>    this.right = right;<br>  }<br>}<br><br>interface Iterator&lt;T&gt; {<br>  current(): T;<br>  next(): T; <br>  valid(): boolean; <br>}<br><br>interface Aggregator { <br>  getIterator(): Iterator&lt;TreeNode&gt; <br>}<br><br>class Tree implements Aggregator {<br>  private root: TreeNode | null;<br>  private size: number;<br><br>  constructor() {<br>    this.root = null;<br>    this.size = 0;<br>  }<br><br>  public getRoot(): TreeNode | null {<br>    return this.root;<br>  }<br><br>  public getSize(): number {<br>    return this.size;<br>  }<br><br>  public add(value: string): void {<br>    const newNode = new TreeNode(value);<br>    if (!this.root) {<br>      this.root = newNode;<br>    } else {<br>      this.insertNode(this.root, newNode);<br>    }<br>    this.size++;<br>  }<br><br>  private insertNode(node: TreeNode, newNode: TreeNode): void {<br>    if (newNode.value &lt; node.value) {<br>      if (!node.left) {<br>        node.left = newNode;<br>      } else {<br>        this.insertNode(node.left, newNode);<br>      }<br>    } else {<br>      if (!node.right) {<br>        node.right = newNode;<br>      } else {<br>        this.insertNode(node.right, newNode);<br>      }<br>    }<br>  }<br><br>  public getIterator(): Iterator&lt;TreeNode&gt; {<br>    if (!this.root) {<br>      throw new Error(&quot;Tree is empty&quot;);<br>    }<br>    return new TreeIterator(this.root);<br>  }<br>}</pre><p>In the example, the in-order traversal technique is applied. Of course, the search method may be different. The in-order traversal is implemented using the TreeIterator class, which provides a way to traverse the tree in the correct order, printing values in ascending order.</p><p>The TreeIterator class has a private field stack: TreeNode[], which acts as a stack. It is used to store the nodes of the tree during iteration. The traverseLeft method prepares the stack in such a way that nodes are visited in the correct sequence. This ensures that in-order traversal is implemented iteratively, not recursively.</p><p>The TreeIterator class also contains methods such as:</p><ul><li><strong>current()</strong>: Returns the current node.</li><li><strong>next()</strong>: moves the iteration to the next node.</li><li><strong>valid()</strong>: checks if there are still elements to traverse.</li></ul><p>Below is the implementation of the TreeIterator class:</p><pre>class TreeIterator implements Iterator&lt;TreeNode&gt; {<br>  private stack: TreeNode[];<br><br>  constructor(root: TreeNode) {<br>    this.stack = [];<br>    this.traverseLeft(root);<br>  }<br><br>  private traverseLeft(node: TreeNode | null): void {<br>    while (node) {<br>      this.stack.push(node);<br>      node = node.left;<br>    }<br>  }<br><br>  public current(): TreeNode {<br>    if (!this.valid()) {<br>      throw new Error(&quot;No current element&quot;);<br>    }<br>    return this.stack[this.stack.length - 1];<br>  }<br><br>  public next(): TreeNode {<br>    if (!this.valid()) {<br>      throw new Error(&quot;No next element&quot;);<br>    }<br>    const node = this.stack.pop()!;<br>    if (node.right) {<br>      this.traverseLeft(node.right);<br>    }<br>    return node;<br>  }<br><br>  public valid(): boolean {<br>    return this.stack.length &gt; 0;<br>  }<br>}</pre><p>The design pattern is started in the IteratorComponent class, its code is below:</p><pre><br>@Component({<br>  selector: &#39;app-iterator&#39;,<br>  standalone: true,<br>  imports: [FormsModule],<br>  template: `<br>  &lt;div&gt;<br>    &lt;h1&gt;Tree Iterator&lt;/h1&gt;<br>    &lt;input [(ngModel)]=&quot;newNodeValue&quot; placeholder=&quot;Enter node value&quot; /&gt;<br>    &lt;button (click)=&quot;addNode()&quot;&gt;Add Node&lt;/button&gt;<br>    &lt;h2&gt;In-Order Traversal:&lt;/h2&gt;<br>    &lt;ul&gt;<br>        @for (node of traversalResult; track node) {<br>        &lt;li&gt;{{ node }}&lt;/li&gt;<br>        }<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>  `, <br>  styleUrl: &#39;./iterator.component.scss&#39;<br>})<br>export class IteratorComponent {<br><br>  tree = new Tree();<br>  newNodeValue: string = &#39;&#39;;<br>  traversalResult: string[] = [];<br> <br>  addNode(): void {<br>    if (this.newNodeValue.trim()) {<br>      this.tree.add(this.newNodeValue);<br>      this.newNodeValue = &#39;&#39;;<br>      this.updateTraversal();<br>    }<br>  }<br><br>  updateTraversal(): void {<br>    const iterator = this.tree.getIterator();<br>    const result: string[] = [];<br>    while (iterator.valid()) {<br>      result.push(iterator.current().value); <br>      iterator.next();<br>    }<br>    this.traversalResult = result;<br>  }<br>}</pre><p>The structure of the Iterator pattern consists of several elements:</p><p><strong>Iterator</strong> interface declares the operations required for traversing a collection: fetching the next element, retrieving the current position, restarting iteration, etc. In our case it is the interface Iterator&lt;T&gt;</p><p><strong>Concrete Iterators</strong> implement algorithms for traversing a collection. In our case it is the interface TreeIterator .</p><p><strong>Collection</strong> interface declares one or multiple methods for getting iterators compatible with the collection. Note that the return type of the methods must be declared as the Iteratorinterface so that the concrete collections can return various kinds of iterators. In our case it is the Aggregator interface</p><p><strong>Concrete Collections</strong> return new instances of a particular concrete iterator class each time the client requests one. In our case it is the Treeclass</p><p><strong>Client</strong> works with both collections and iterators via their interfaces. In our case it is the IteratorComponentclass</p><h3>Summary</h3><p>The main use of the <strong>Iterator </strong>pattern is to provide a uniform and convenient way to iterate through the elements of a collection (e.g., list, tree, set), regardless of the internal structure of that collection.</p><p>Using a for loop is much faster than Iteration. In Angular, forloops can also leverage the track method, which functions similarly to an index in a database. The <strong>Iterator </strong>design pattern is primarily focused on separating the logic of iteration from the collection.</p><p>Materials:</p><ol><li><em>Java. Wzorce projektowe</em>. Translation: Piotr Badarycz. Original title: <em>Java design patterns. A Tutorial. </em>Author: James William Cooper</li><li><a href="https://refactoring.guru/design-patterns/iterator">https://refactoring.guru/design-patterns/iterator</a></li></ol><p>My other articles related to Design Patterns in Angular:</p><p>Structural patterns:<br><a href="https://medium.com/design-patterns-adapter-in-angular/design-patterns-adapter-in-angular-ca018478a93b">Design Pattern — Adapter in Angular</a><br><a href="https://medium.com/design-patterns-composite-in-angular/wzorce-projektowe-kompozytowe-w-angular-445c289e4e9f">Design Pattern — Composite in Angular</a><br><a href="https://medium.com/design-patterns-decorator-in-angular/design-patterns-decorator-in-angular-7957bbdbfe06">Design Pattern — Decorator in Angular</a><br><a href="https://medium.com/design-patterns-fasada/design-patterns-facade-in-angular-90bff55aee48">Design Pattern — Facade in Angular</a><br><a href="https://medium.com/design-patterns-proxy-in-angular/design-patterns-proxy-in-angular-8661c1049252">Design Pattern — Proxy in Angular</a></p><p>Creational patterns:<br><a href="https://medium.com/design-patterns-builder-in-angular/design-patterns-builder-in-angular-c9a05b91385f">Design Pattern — Builder in Angular</a><br><a href="https://medium.com/design-pattern-prototype-in-angular/design-pattern-prototype-in-angular-1f6e224bb4f9">Design Pattern — Factory (Simple Factory) in Angular</a><br><a href="https://medium.com/design-pattern-prototype-in-angular/design-pattern-prototype-in-angular-1f6e224bb4f9">Design Pattern — Prototype in Angular</a></p><p>Behavioral patterns:<br><a href="https://medium.com/design-patterns-chain-of-responsibility-in-angular/design-patterns-chain-of-responsibility-in-angular-5bd0b10b011d">Design Pattern — Chain of Responsibility in Angular</a><br><a href="https://medium.com/design-patterns-memento-in-angular/design-patterns-memento-in-angular-a4d8985f4771">Design Pattern — Memento in Angular</a><br><a href="https://medium.com/design-patterns-observer-in-angular/behavioral-patterns-are-design-patterns-that-deal-with-the-ways-objects-communicate-with-each-other-2b4ff0cba9e5">Design Pattern — Observer in Angular</a></p><p>I’m not good at English. I write articles to practice English.</p><p>I wanted to mention that there may be some mistakes in the articles related to the English language. I apologize for that. If I will notice any, I will correct them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9508f3b69d08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-patterns-iterator-in-angular/design-patterns-iterator-in-angular-9508f3b69d08">Design Pattern — Iterator in Angular</a> was originally published in <a href="https://medium.com/design-patterns-iterator-in-angular">Design Pattern — Iterator in Angular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>