<?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 Ania Sniadek ⚡️ on Medium]]></title>
        <description><![CDATA[Stories by Ania Sniadek ⚡️ on Medium]]></description>
        <link>https://medium.com/@sniadek97?source=rss-2928654bf9b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1BHEKJYHnT2q5ZVYGAVl8w.jpeg</url>
            <title>Stories by Ania Sniadek ⚡️ on Medium</title>
            <link>https://medium.com/@sniadek97?source=rss-2928654bf9b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:09:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sniadek97/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[Mastering Tailwind CSS in Your Angular Application ]]></title>
            <link>https://blog.devgenius.io/mastering-tailwind-css-in-your-angular-application-c2fe5b69468a?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2fe5b69468a</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 18:45:24 GMT</pubDate>
            <atom:updated>2024-04-26T11:24:26.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-CEUJGtmAuHvU13c" /><figcaption>Photo by <a href="https://unsplash.com/@jacksonsophat?utm_source=medium&amp;utm_medium=referral">Jackson Sophat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Tailwind CSS has revolutionized the way developers approach styling in web applications. With its utility-first approach, Tailwind allows for efficient development by providing a wide range of pre-built CSS classes. In this article, we’ll explore how you can leverage the power of Tailwind CSS to enhance your Angular development workflow. Whether you’re a seasoned Angular developer or just getting started, this guide will show you how to integrate Tailwind CSS effectively and create stunning user interfaces with ease. So, let’s dive in! 🏄‍♂️</p><h4>Create Angular project</h4><p>If you already have an existing Angular project, you can skip this step. Otherwise, let’s create a new Angular project by following these simple instructions 👇</p><pre>$ ng new project-name<br>$ cd project-name</pre><h4>Install Tailwind CSS</h4><p>The next step is to add Tailwind CSS to our project. We’ll install Tailwind CSS via npm and then run the initialization command to generate a tailwind.config.js file. Let&#39;s get started!</p><pre>$ npm install -D tailwindcss postcss autoprefixer<br>$ npx tailwindcss init</pre><h4>Configure Tailwind config file</h4><p>Now, let’s configure the tailwind.config.js file by adding paths to all of your template files. This step ensures that Tailwind CSS is properly applied to your Angular project.</p><pre>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [<br>    &quot;./src/**/*.{html,ts}&quot;,<br>  ],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><p>In this file, we can add any additional configurations we need, such as colors, screens, spacing, plugins and more.</p><h4>Add Tailwind Directives to Your CSS/SCSS</h4><p>Next, let’s add the @tailwind directives for each of Tailwind’s layers to your ./src/styles.css or ./src/styles.scss file. This step will enable Tailwind CSS in your Angular project, allowing you to start using its utility classes. Let&#39;s proceed by adding these directives to our CSS/SCSS file.</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><h4>Fix @tailwind Unknown At-Rule Warning</h4><p>If you come across the “unknown at rule @tailwind” warning, don’t worry! I’ll show you how to fix it. If you haven’t experienced this issue, feel free to skip this step and move on to the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Os3GyUhDZIxHu4QamLz7Cg.png" /></figure><p>The @tailwind unknown at-rule warning is a common issue that occurs when using Tailwind with VSCode. To resolve this, we need to configure VSCode to ignore the warning by adding a custom setting in your workspace or user settings. Let’s fix this issue by opening the settings.json file and adding the following line:</p><pre>{<br>  // If you are using CSS file in your project<br>  &quot;css.lint.unknownAtRules&quot;: &quot;ignore&quot;,<br>  // If you are using SCSS file in your project<br>  &quot;scss.lint.unknownAtRules&quot;: &quot;ignore&quot;<br>}</pre><h4>Start using Tailwind</h4><p>Now that your Angular application is ready, you can start using Tailwind CSS. To ensure everything is set up correctly, let’s start your application using the following command:</p><pre>$ ng serve</pre><p>Once your application is running without any issues, we can start using Tailwind in our project 🙌</p><pre>&lt;h1 class=&quot;text-xl font-bold&quot;&gt;Hello world!&lt;/h1&gt;</pre><p>Copy and paste this code into your app.component.html file and check if it&#39;s working as expected.</p><h4>Prettier Plugin for Tailwind CSS</h4><p>Formatting Tailwind CSS code is made easy with the help of Prettier. This plugin scans your templates for class attributes containing Tailwind CSS classes and automatically sorts those classes according to our recommended class order. Now, you can stop worrying about class sorting and focus on building amazing user interfaces with Tailwind CSS. Let’s see how to set up and use this plugin in your Angular project.</p><p>First, we need to install Prettier in our application. If you already have it installed, you can skip this step.</p><pre>$ npm install prettier --save-dev</pre><p>Then, we need to create a .prettierrc configuration file in our root project directory.</p><pre>$ touch .prettierrc</pre><p>Alright, now let’s add the Prettier Tailwind plugin to our project. Install prettier-plugin-tailwindcss as a dev dependency 👇</p><pre>$ npm install -D prettier prettier-plugin-tailwindcss</pre><p>Then, add the plugin to your Prettier configuration file .prettierrc:</p><pre>{<br>  &quot;plugins&quot;: [&quot;prettier-plugin-tailwindcss&quot;]<br>}</pre><p>Great! Now, let’s test if it’s working by adding some classes to our app.component.html file. For example, we can add the underline class in the middle of our existing classes.</p><pre>&lt;h1 class=&quot;text-xl underline font-bold&quot;&gt;Hello world!&lt;/h1&gt;</pre><p>After saving the file, our classes were reordered, and now it looks like this:</p><pre>&lt;h1 class=&quot;text-xl font-bold underline&quot;&gt;Hello world!&lt;/h1&gt;</pre><h4>Conclusion 🌟</h4><p>In conclusion, integrating Tailwind CSS into your Angular project not only simplifies styling but also enhances your development workflow. With its utility-first approach and the addition of the Prettier plugin, you can efficiently build beautiful user interfaces while maintaining clean and organized code. Whether you’re working on a small project or a large-scale application, Tailwind CSS proves to be a valuable tool for developers.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2fe5b69468a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mastering-tailwind-css-in-your-angular-application-c2fe5b69468a">Mastering Tailwind CSS in Your Angular Application 💥</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New control flow in Angular 17 ]]></title>
            <link>https://javascript.plainenglish.io/new-control-flow-in-angular-17-5fe4407e96ff?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe4407e96ff</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 13:35:02 GMT</pubDate>
            <atom:updated>2024-04-06T11:59:59.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wcbFIbnfDvYvKMJ2" /><figcaption>Photo by <a href="https://unsplash.com/@clarktibbs?utm_source=medium&amp;utm_medium=referral">Clark Tibbs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Angular 17 introduced a new built-in control flow syntax for managing the flow of your application’s templates, providing a simpler approach. These blocks empower programmers to conditionally display, hide, and repeat elements within the templates, replacing the older directive-based method with *ngIf, *ngFor, and ngSwitch. You can learn more by checking out examples below 👇.</p><h4>Conditional statements →@if</h4><p>The updated @if syntax in the built-in control flow displays its content conditionally when its condition expression evaluates to true, serving the same purpose as the old *ngIf directive.</p><pre>@if (user.role === &#39;admin&#39;) {<br>  &lt;h2&gt;Welcome Admin!&lt;/h2&gt;<br>}</pre><p>After an @if block, you have the option to include any number of @else if blocks and one @else block.</p><pre>@if (user.role === &#39;admin&#39;) {<br>  &lt;h2&gt;Welcome Admin!&lt;/h2&gt;<br>} @else if (user.role === &#39;user&#39;) {<br>  &lt;h2&gt;Welcome User!&lt;/h2&gt;<br>} @else {<br>  &lt;h2&gt;Welcome Guest!&lt;/h2&gt;<br>}</pre><p>You can also add a reference to the outcome of an @if condition and use it inside the block’s content.</p><pre>@if (user.role; as role) {<br>  &lt;h2&gt;{{ role }}&lt;/h2&gt;<br>}<br><br>&lt;!-- or with async pipe --&gt;<br>@if (user$ | async; as user) {<br>  &lt;h2&gt;{{ user.role }}&lt;/h2&gt;<br>}</pre><h4>Conditional statements →@switch</h4><p>An improved version of code structure with @if can be achieved using the new built-in control flow @switch syntax, which is meant to replace the old ngSwitch directive.</p><pre>@switch (user.role) {<br>  @case (&#39;admin&#39;) {<br>    &lt;h2&gt;Welcome Admin!&lt;/h2&gt;<br>  }<br>  @case (&#39;user&#39;) {<br>    &lt;h2&gt;Welcome User!&lt;/h2&gt;<br>  }<br>  @default {<br>    &lt;h2&gt;Welcome Guest!&lt;/h2&gt;<br>  }<br>}</pre><h4>For loop -&gt; @for</h4><p>Last but not least, there’s the new built-in control syntax @for, which iterates through its content for each item in a collection. It is a replacement for the previous *ngFor directive.</p><pre>@for(user of users; track user.id) {<br>  &lt;h3&gt;{{ user.name }}&lt;/h3&gt;<br>}</pre><p>The @for syntax offers more efficient and optimized solutions compared to *ngFor. In this solution the track statement is required. This statement is essential for monitoring items by reference, ensuring optimized performance by minimizing unnecessary change detection processes when data is modified.</p><p>Optionally, you can include an @empty section right after the @for block content. The content inside the @empty block is shown when there are no items.</p><pre>@for(user of users; track user.id) {<br>  &lt;h3&gt;{{ user.name }}&lt;/h3&gt;<br>} @empty {<br>  &lt;h2&gt;There are no users.&lt;/h2&gt;<br>}</pre><p>The @for syntax also provides additional useful implicit variables such as: $index, $count, $first, $last, $even, and $odd :</p><ul><li>$index — index of the current row.</li><li>$count — number of items in a collection.</li><li>$first — boolean value that indicates if the current row is the first row in the collection.</li><li>$last — boolean value that indicates if the current row is the last row in the collection.</li><li>$even — boolean value that indicates if the current index row is an even number</li><li>$odd — boolean value that indicates if the current index row is an odd number.</li></ul><h4>Wrapping up 🎉</h4><p>The new syntax in Angular looks like what you’d see in other programming languages, making your templates easier to understand, especially if you’re new to Angular or coding in general. With this simpler syntax, you’re less likely to make mistakes compared to the older directives. Unlike before, you don’t have to import any additional modules to use these new control flow features. They’re already built-in, making your code cleaner and reducing boilerplate 🙌.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe4407e96ff" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/new-control-flow-in-angular-17-5fe4407e96ff">New control flow in Angular 17 🎉</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create and Use React Context ✨]]></title>
            <link>https://blog.devgenius.io/how-to-create-and-use-react-context-57e3a9bcaada?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/57e3a9bcaada</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-tips]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 16:50:47 GMT</pubDate>
            <atom:updated>2024-02-05T17:00:41.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GrGUtaqIJl-aGj0C" /><figcaption>Photo by <a href="https://unsplash.com/@baciutudor?utm_source=medium&amp;utm_medium=referral">Tudor Baciu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React Context is a powerful feature that allows you to share state between components without having to pass props down through every level of your component tree. In this article, we’ll explore how to create and use React Context by building a simple authentication context 🛠️.</p><h4>Understanding React Context 🌐</h4><p>React Context provides a way to pass data through the component tree without having to pass props manually at every level. It consists of two main parts: the Provider and the useContext hook.</p><p>In this example, we have an AuthContext with an associated AuthContextProvider. The provider wraps our application and makes the authentication state available to any component that accesses it.</p><h4>Creating the AuthContext 🔧</h4><p>Let’s create the AuthContext.tsx file:</p><pre>import {<br>  createContext,<br>  FC,<br>  PropsWithChildren,<br>  useContext,<br>  useState,<br>} from &#39;react&#39;;<br><br>// Define the type for the authentication context<br>type AuthContextType = {<br>  isAuthenticated: boolean;<br>  login: () =&gt; void;<br>  logout: () =&gt; void;<br>};<br><br>// Create the AuthContext using createContext and provide its type<br>const AuthContext = createContext&lt;AuthContextType | undefined&gt;(undefined);<br><br>const AuthContextProvider: FC&lt;PropsWithChildren&gt; = ({ children }) =&gt; {<br>  // State to track the authentication status<br>  const [isAuthenticated, setIsAuthenticated] = useState(false);<br><br>  // Function to set the isAuthenticated state to true, representing a successful login<br>  const login = () =&gt; {<br>    setIsAuthenticated(true);<br>  };<br><br>  // Function to set the isAuthenticated state to false, representing a logout<br>  const logout = () =&gt; {<br>    setIsAuthenticated(false);<br>  };<br><br>  // Return the AuthContext.Provider, wrapping the children with the authentication context<br>  return (<br>    &lt;AuthContext.Provider value={{ isAuthenticated, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br><br>// useAuthContext is a custom hook that simplifies consuming the AuthContext<br>const useAuthContext = () =&gt; {<br>  // Use the useContext hook to access the AuthContext<br>  const context = useContext(AuthContext);<br><br>  // Throw an error if useAuthContext is not used within an AuthContextProvider<br>  if (!context) {<br>    throw new Error(<br>      &#39;useAuthContext must be used within an AuthContextProvider&#39;<br>    );<br>  }<br><br>  // Return the authentication context<br>  return context;<br>};<br><br>// Export the AuthContextProvider and useAuthContext for use in other components<br>export { AuthContextProvider, useAuthContext };</pre><p>Here, AuthContext is created using createContext, and its type is defined. The AuthContextProvider component wraps the children with the provider, making the authentication state available to all nested components.</p><h4>Providing the Context to the App 🚀</h4><p>In your index.tsx file, wrap App component with AuthContextProvider:</p><pre>import { StrictMode } from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br><br>import { App } from &#39;./App&#39;;<br>import { AuthContextProvider } from &#39;./AuthContext&#39;;<br><br>const root = createRoot(document.getElementById(&#39;app&#39;));<br><br>root.render(<br>  &lt;StrictMode&gt;<br>    &lt;AuthContextProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/AuthContextProvider&gt;<br>  &lt;/StrictMode&gt;<br>);</pre><p>By wrapping your App component with AuthContextProvider, the authentication context is available to all components in the app.</p><h4>Using the AuthContext in App 🔍</h4><p>Import and use useAuthContext hook to access the authentication context, for example in the App.tsx component:</p><pre>import { FC } from &#39;react&#39;;<br>import { useAuthContext } from &#39;./AuthContext&#39;;<br><br>import &#39;./style.css&#39;;<br><br>export const App: FC = () =&gt; {<br>  const { isAuthenticated, login, logout } = useAuthContext();<br><br>  return (<br>    &lt;&gt;<br>      &lt;p&gt;User is {isAuthenticated ? &#39;authenticated&#39; : &#39;not authenticated&#39;}&lt;/p&gt;<br>      {!isAuthenticated ? (<br>        &lt;button onClick={login}&gt;Login&lt;/button&gt;<br>      ) : (<br>        &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>};</pre><p>This component renders content based on the authentication status from the useAuthContext hook.</p><h4>Conclusion 🌟</h4><p>React Context is a powerful tool for managing state in React applications. Creating a context for authentication is just one example. By following this pattern, you can extend this concept to manage and share other types of global state across your application, making your code organized and easy to reuse 🙌.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇. If you want to see the whole example, you can do it here on <a href="https://stackblitz.com/edit/how-to-create-and-use-react-context">StackBlitz ⚡️</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57e3a9bcaada" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-create-and-use-react-context-57e3a9bcaada">How to Create and Use React Context ✨</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing Components as Props in React ]]></title>
            <link>https://blog.devgenius.io/passing-components-as-props-in-react-60dca9aae7f5?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/60dca9aae7f5</guid>
            <category><![CDATA[react-tips]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 17:05:49 GMT</pubDate>
            <atom:updated>2024-01-31T18:52:00.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b6Wf1qy0wcoi3Htf" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In React development, passing components as props is a powerful and flexible pattern that allows developers to create reusable and dynamic UI structures. It’s like having building blocks you can use and reuse to create all sorts of things in your app. This makes your code more flexible and easier to manage. In this article, we’ll dive into this idea of passing components as props in React, using TypeScript to make things even better. We’ll look at three different ways to do this, and I’ll show you with simple examples. It’s like learning three secret codes to make your React components even more awesome! Let’s jump in and have some fun with it 🚀.</p><h4><strong>Way #1: Function as Prop Example </strong>🛠️</h4><pre>import { FC, PropsWithChildren, ReactNode } from &#39;react&#39;;<br><br>const MainComponent: FC&lt;PropsWithChildren&lt;{ customHeader?: () =&gt; ReactNode }&gt;&gt; =<br>  ({ customHeader, children }) =&gt; {<br>    const header = customHeader?.();<br>    return (<br>      &lt;&gt;<br>        {header ? header : &lt;h1&gt;Hello!&lt;/h1&gt;}<br>        {children}<br>      &lt;/&gt;<br>    );<br>  };<br><br>const HeaderComponent: FC = () =&gt; {<br>  return &lt;h4&gt;Function as prop example header!&lt;/h4&gt;;<br>};<br><br>export const FunctionAsPropExample: FC = () =&gt; {<br>  const renderCustomHeader = () =&gt; &lt;HeaderComponent /&gt;;<br>  return (<br>    &lt;MainComponent customHeader={renderCustomHeader}&gt;<br>      &lt;span&gt;With custom header&lt;/span&gt;<br>    &lt;/MainComponent&gt;<br>  );<br>};</pre><p>The first method involves using function props, where a function serves as a prop, offering a dynamic way to customize component behavior. In this example, the MainComponent accepts a customHeader function, providing developers with the ability to inject dynamic content into the header. The FunctionAsPropExample demonstrates this by passing a function that returns the HeaderComponent.</p><h4><strong>Way #2: ReactElement as Prop Example </strong>⚙️</h4><pre>import { FC, PropsWithChildren, ReactNode } from &#39;react&#39;;<br><br>const MainComponent: FC&lt;PropsWithChildren&lt;{ customHeader?: ReactNode }&gt;&gt; = ({<br>  customHeader,<br>  children,<br>}) =&gt; {<br>  return (<br>    &lt;&gt;<br>      {customHeader ? customHeader : &lt;h1&gt;Hello!&lt;/h1&gt;}<br>      {children}<br>    &lt;/&gt;<br>  );<br>};<br><br>const HeaderComponent: FC = () =&gt; {<br>  return &lt;h4&gt;React Element as prop example header!&lt;/h4&gt;;<br>};<br><br>export const ReactElementAsPropExample: FC = () =&gt; {<br>  return (<br>    &lt;MainComponent customHeader={&lt;HeaderComponent /&gt;}&gt;<br>      &lt;span&gt;With custom header&lt;/span&gt;<br>    &lt;/MainComponent&gt;<br>  );<br>}</pre><p>In the second method, we simplify the process by directly assigning a component as a prop. This approach minimizes the need for an intermediate function, providing a more straightforward way to customize components. In this example, the ReactElementAsPropExample component directly passes the HeaderComponent as a prop to the MainComponent.</p><h4><strong>Way #3: Component as Prop Example 🔩</strong></h4><pre>import { FC, PropsWithChildren } from &#39;react&#39;;<br><br>const MainComponent: FC&lt;PropsWithChildren&lt;{ CustomHeader?: FC }&gt;&gt; = ({<br>  CustomHeader,<br>  children,<br>}) =&gt; {<br>  return (<br>    &lt;&gt;<br>      {CustomHeader ? &lt;CustomHeader /&gt; : &lt;h1&gt;Hello!&lt;/h1&gt;}<br>      {children}<br>    &lt;/&gt;<br>  );<br>};<br><br>const HeaderComponent: FC = () =&gt; {<br>  return &lt;h4&gt;Component as prop example header!&lt;/h4&gt;;<br>};<br><br>export const ComponentAsPropExample: FC = () =&gt; {<br>  return (<br>    &lt;MainComponent CustomHeader={HeaderComponent}&gt;<br>      &lt;span&gt;With custom header&lt;/span&gt;<br>    &lt;/MainComponent&gt;<br>  );<br>};</pre><p>The third method introduces a more direct way to pass components as props by accepting a whole component as a prop. In Example 3, the MainComponent takes a CustomHeader prop of type FC (Functional Component) and renders it directly, providing a clean and concise method for component customization.</p><h4>Wrapping up 🌟</h4><p>You might be wondering why bother with passing components as props. The answer lies in the organizational benefits and increased reusability it brings to your code. This technique allows components to be easily integrated into various parts of your application. Embrace these methods, and you’ll soon discover new ways to compose and organize your components for more efficient development. Happy coding! 🙌</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇. If you want to see the whole example, you can do it here on <a href="https://stackblitz.com/edit/passing-a-components-as-props">StackBlitz ⚡️</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60dca9aae7f5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/passing-components-as-props-in-react-60dca9aae7f5">Passing Components as Props in React 🧩</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring switchMap, mergeMap, and concatMap in RxJS ]]></title>
            <link>https://javascript.plainenglish.io/exploring-switchmap-mergemap-and-concatmap-in-rxjs-bc943a294580?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc943a294580</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs-operators]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 13:19:35 GMT</pubDate>
            <atom:updated>2023-08-04T01:02:22.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gl-SXalmHZjwoMV2" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In RxJS, switchMap, mergeMap and concatMap are higher-order mapping operators used with observable streams. They enable the transformation of one stream of data into another stream. However, they differ in how they handle multiple inner observable emissions and manage their subscriptions. Let’s explore these differences 👇</p><h4>switchMap 🔁</h4><ul><li>The switchMap operator takes each value from the source observable and maps it to an inner observable.</li><li>When a new source value arrives, it unsubscribes from the previous inner observable and subscribes to the new one.</li><li>This means that if new emissions arrive from the source observable before the inner observable completes, the previous inner observable is terminated and the new one starts processing the data.</li><li>Use switchMap when you only care about the most recent inner observable and want to cancel previous inner observables when a new one arrives.</li></ul><p>See example below👇</p><pre>import { fromEvent, interval } from &#39;rxjs&#39;;<br>import { switchMap } from &#39;rxjs/operators&#39;;<br><br>// Create a source observable from a click event<br>const click$ = fromEvent(document, &#39;click&#39;);<br><br>// Use switchMap to switch to an inner observable (interval) on each click event<br>const example$ = click$.pipe(<br>  switchMap(() =&gt; interval(1000)) // Emits 0, 1, 2, 3, ... every 1 second<br>);<br><br>// Subscribe to the final switched observable<br>example$.subscribe(value =&gt; console.log(value));<br><br>// When you click the document, the interval starts and switches on each new click<br>// The previous interval is canceled and a new interval starts</pre><h4>mergeMap/flatMap 🔄</h4><ul><li>The mergeMap operator maps each value from the source observable to an inner observable.</li><li>It subscribes to all the inner observables simultaneously and merges their emissions into a single observable stream.</li><li>The order of the emissions from inner observables is not guaranteed. They can mix together based on which inner observable emits values faster.</li><li>Use mergeMap when you want to merge the output of all inner observables and receive the emissions as they happen, irrespective of their order.</li></ul><p>See example below 👇</p><pre>import { of, from } from &#39;rxjs&#39;;<br>import { mergeMap, delay, finalize } from &#39;rxjs/operators&#39;;<br><br>// Simulate API calls with delays<br>const apiCall1$ = of(&#39;API Response 1&#39;).pipe(delay(2000));<br>const apiCall2$ = of(&#39;API Response 2&#39;).pipe(delay(1500));<br>const apiCall3$ = of(&#39;API Response 3&#39;).pipe(delay(3000));<br><br>// Use mergeMap to make the API calls and merge their results into a single stream<br>const example$ = from([apiCall1$, apiCall2$, apiCall3$])<br>  .pipe(<br>    mergeMap((call) =&gt; call),<br>    finalize(() =&gt; console.log(&#39;All API calls completed!&#39;))<br>  );<br><br>// Subscribe to the observable<br>example$.subscribe(result =&gt; console.log(result));<br><br>// The inner observables are running simultaneously and emit values as they happen</pre><h4>concatMap 🔗</h4><ul><li>The concatMap operator projects each source value to an inner observable.</li><li>It subscribes to the inner observables sequentially, waiting for each one to complete before moving on to the next.</li><li>The order of the emissions from inner observables is preserved, as each inner observable must complete before the next one starts processing.</li><li>Use concatMap when you want to maintain the order of emissions from the inner observables and process them one after another.</li></ul><p>See example below 👇</p><pre>import { of, from } from &#39;rxjs&#39;;<br>import { concatMap, delay, finalize } from &#39;rxjs/operators&#39;;<br><br>// Simulate API calls with delays<br>const apiCall1$ = of(&#39;API Response 1&#39;).pipe(delay(2000));<br>const apiCall2$ = of(&#39;API Response 2&#39;).pipe(delay(1500));<br>const apiCall3$ = of(&#39;API Response 3&#39;).pipe(delay(3000));<br><br>// Use concatMap to make the API calls sequentially and preserve their order<br>const example$ = from([apiCall1$, apiCall2$, apiCall3$])<br>  .pipe(<br>    concatMap((call) =&gt; call),<br>    finalize(() =&gt; console.log(&#39;All API calls completed!&#39;))<br>  );<br><br>// Subscribe to the observable<br>example$.subscribe(result =&gt; console.log(result));<br><br>// The inner observables run sequentially, one after the other,<br>// and the order of emissions from inner observables is preserved.</pre><h4>Wrapping up 🎉</h4><p>The article explains the differences between switchMap, mergeMap, and concatMap in an easy-to-understand way. It shows how they handle data in different ways and when to use each one. It&#39;s a useful guide to pick the right method for transforming observable data effectively.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc943a294580" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/exploring-switchmap-mergemap-and-concatmap-in-rxjs-bc943a294580">Exploring switchMap, mergeMap, and concatMap in RxJS 🔍</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Most Useful JavaScript Array Methods ]]></title>
            <link>https://javascript.plainenglish.io/the-most-useful-javascript-array-methods-2515f0709854?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2515f0709854</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functions-in-javascript]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 15:08:05 GMT</pubDate>
            <atom:updated>2023-09-25T00:18:06.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqtFdFjtfzgQ0FB1" /><figcaption>Photo by <a href="https://unsplash.com/@jay_zhang?utm_source=medium&amp;utm_medium=referral">Jay Zhang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Unlock the true potential of JavaScript arrays with this article on the most useful array methods. Learn how these methods can simplify your code and enhance your programming skills. From adding and removing elements to iterating and transforming arrays, this article covers essential methods like push, pop, forEach, map, filter, and more. Whether you’re a beginner or an experienced developer, this article provides valuable insights to help you harness the power of JavaScript arrays and optimize your coding workflow.</p><h4>forEach</h4><p>The forEach method is used to iterate over the elements of an array and execute a provided callback function for each element.</p><p>This method takes a callback function as its parameter, which can have up to three arguments:</p><ul><li>currentValue (required): The current element being processed in the array.</li><li>index (optional): The index of the current element being processed.</li><li>array (optional): The array on which the forEach method was called.</li></ul><pre>const numbers = [1, 2, 3];<br><br>numbers.forEach((currentValue, index) =&gt; {<br>  console.log(`Element at index ${index}: ${currentValue}`);<br>});<br><br>// Output:<br>// Element at index 0: 1<br>// Element at index 1: 2<br>// Element at index 2: 3</pre><p>The forEach method does not return a value. It executes the provided callback function for each element in the array.</p><h4>map</h4><p>The map method is used to create a new array by applying a provided callback function to each element of the calling array. It allows for transforming the elements of the array based on the logic defined in the callback function.</p><p>This method takes a callback function as its parameter, which can have up to three arguments:</p><ul><li>currentValue (required): The current element being processed in the array.</li><li>index (optional): The index of the current element being processed.</li><li>array (optional): The array on which the map method was called.</li></ul><pre>const numbers = [1, 2, 3];<br><br>const multiplied = numbers.map(currentValue =&gt; currentValue * 2);<br><br>console.log(multiplied);<br>// Output: [2, 4, 6]</pre><p>The map method returns a new array with the results of calling the provided callback function on each element of the original array.</p><h4>filter</h4><p>The filter method is used to create a new array with all the elements that pass a provided test. It allows for filtering elements based on a specified condition and returning a new array containing only the elements that satisfy the condition.</p><p>This method takes a callback function as its parameter, which can have up to three arguments:</p><ul><li>currentValue (required): The current element being processed in the array.</li><li>index (optional): The index of the current element being processed.</li><li>array (optional): The array on which the filter method was called.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const evenNumbers = numbers.filter(currentValue =&gt; currentValue % 2 === 0);<br><br>console.log(evenNumbers);<br>// Output: [2, 4]</pre><p>The filter method returns a new array containing the elements from the original array that satisfy the condition specified in the callback function.</p><h4>concat</h4><p>The concat method is used to merge two or more arrays, creating a new array that contains the elements of the original arrays. It does not modify the original arrays.</p><p>This method accepts one or more arrays as parameters to be concatenated with the calling array.</p><pre>const numbers1 = [1, 2, 3];<br>const numbers2 = [4, 5, 6];<br><br>const numbers = numbers1.concat(numbers2);<br><br>console.log(numbers);<br>// Output: [1, 2, 3, 4, 5, 6]</pre><p>The concat method returns a new array that contains the elements of the calling array followed by the elements of the provided arrays.</p><h4>push</h4><p>The push method is used to add one or more elements to the end of an array. It modifies the original array by appending the specified elements to its end.</p><p>This method accepts one or more parameters, which represent the elements to be added to the end of the array.</p><pre>const numbers = [1, 2, 3];<br><br>numbers.push(4);<br><br>console.log(numbers);<br>// Output: [1, 2, 3, 4]</pre><p>The push method returns the new length of the modified array after the elements have been added.</p><h4>pop</h4><p>The pop method is used to remove the last element from an array. It modifies the original array by removing the last element and returns that element.</p><p>This method does not accept any parameters.</p><pre>const numbers = [1, 2, 3];<br><br>numbers.pop();<br><br>console.log(numbers);<br>// Output: [1, 2]</pre><p>The pop method returns the element that was removed from the end of the array.</p><h4>splice</h4><p>The splice method is used to modify an array by adding, removing, or replacing elements at a specified index. It allows for flexible array manipulation by changing the contents of the array in place.</p><p>This method accepts multiple parameters:</p><ul><li>start (required): The index at which the modification should begin.</li><li>deleteCount (optional): The number of elements to remove starting from the start index. If set to 0, no elements are removed.</li><li>itemsToAdd (optional): Elements to be inserted at the start index.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br><br>numbers.splice(1, 2);<br><br>console.log(numbers);<br>// Output: [1, 4, 5]</pre><p>The splice method returns an array containing the elements that were removed.</p><h4>shift</h4><p>The shift method is used to remove the first element from an array. It modifies the original array by shifting all remaining elements to a lower index and updates the length of the array.</p><p>This method does not accept any parameters.</p><pre>const numbers = [1, 2, 3];<br><br>numbers.shift();<br><br>console.log(numbers);<br>// Output: [2, 3]</pre><p>The shift method returns the element that was removed from the beginning of the array.</p><h4>unshift</h4><p>The unshift method is used to add one or more elements to the beginning of an array. It modifies the original array by inserting the specified elements at the start and shifting the existing elements to higher indices.</p><p>This method accepts one or more parameters, which represent the elements to be added to the beginning of the array.</p><pre>const numbers = [2, 3];<br><br>const length = numbers.unshift(1);<br><br>console.log(numbers);<br>// Output: [1, 2, 3]</pre><p>The unshift method returns the new length of the modified array after the elements have been added.</p><h4>indexOf</h4><p>The indexOf method is used to find the index of the first occurrence of a specified value within an array.</p><p>This method accepts one required parameter, which is the element to search for within the array.</p><pre>const numbers = [1, 2, 3];<br><br>const index = numbers.indexOf(3);<br><br>console.log(index);<br>// Output: 2</pre><p>The indexOf method returns the index of the first occurrence of the search element within the array. If the element is not found, it returns -1.</p><h4>find</h4><p>The find method is used to retrieve the first element in an array that satisfies a given condition.</p><p>This method accepts one required parameter, which is a callback function that is called for each element in the array. It takes three arguments: element, index, and array. The callback function should return true if the element satisfies the desired condition, otherwise false.</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const result = numbers.find(element =&gt; element &gt; 3);<br><br>console.log(result);<br>// Output: 4</pre><p>The find method returns the value of the first element in the array that satisfies the condition specified by the callback function. If no element is found, it returns undefined.</p><h4>some</h4><p>The some method is used to check if at least one element in an array satisfies a given condition.</p><p>This method accepts one required parameter, which is a callback function that is called for each element in the array. It takes three arguments: element, index, and array. The callback function should return true if the element satisfies the desired condition, otherwise false.</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const result = numbers.some(element =&gt; element &gt; 3);<br><br>console.log(result);<br>// Output: true</pre><p>The some method returns a Boolean value. It returns true if at least one element in the array satisfies the condition specified by the callback function. Otherwise, it returns false.</p><h4>Wrapping up</h4><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2515f0709854" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-most-useful-javascript-array-methods-2515f0709854">The Most Useful JavaScript Array Methods 🤌</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Form Control in Angular ]]></title>
            <link>https://javascript.plainenglish.io/custom-form-control-in-angular-8bd98213d06c?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd98213d06c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Thu, 25 May 2023 18:16:51 GMT</pubDate>
            <atom:updated>2024-09-12T03:57:47.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MjbMYVNhI3TGu4Cj" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Angular offers an expanded set of built-in form controls for creating dynamic and interactive forms. However, there are cases when these controls do not meet certain requirements or design preferences. This is where the ability to create custom form controls in Angular comes in handy 🙌.</p><h4><strong>Custom form control</strong></h4><p>To create a custom form control in Angular, you can follow steps below 👇</p><p>1. Create component for a custom form control.</p><pre>$ ng generate component custom-input</pre><p>2. In the component’s TypeScript file, implement the ControlValueAccessor interface.</p><pre>import { Component } from &#39;@angular/core&#39;<br>import { ControlValueAccessor } from &#39;@angular/forms&#39;<br><br>@Component({<br>  selector: &#39;app-custom-input&#39;,<br>  templateUrl: &#39;./custom-input.component.html&#39;,<br>  styleUrls: [&#39;./custom-input.component.css&#39;]<br>})<br>export class CustomInputComponent implements ControlValueAccessor {}</pre><p>3. Provide the NG_VALUE_ACCESSOR token and set it to use the forwardRef function to reference your custom control.</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;<br><br>@Component({<br>  selector: &#39;app-custom-input&#39;,<br>  templateUrl: &#39;./custom-input.component.html&#39;,<br>  styleUrls: [&#39;./custom-input.component.css&#39;],<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; CustomInputComponent),<br>      multi: true<br>    }<br>  ]<br>})<br>export class CustomInputComponent implements ControlValueAccessor {}</pre><blockquote><em>💡</em> <strong>Learn how to efficiently manage API requests in Angular applications using RxJS operators:</strong></blockquote><p><a href="https://differ.blog/inplainenglish/optimizing-api-calls-in-angular-with-rxjs-d06311">Optimize Angular API Calls with RxJS</a></p><blockquote><em>👉</em> To read more such acrticles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><p>4. Implement the ControlValueAccessor methods.</p><ul><li>writeValue(obj: any): void — updates the form control’s value based on the provided value parameter.</li><li>registerOnChange(fn: any): void — registers a callback function to be called when the form control value changes.</li><li>registerOnTouched(fn: any): void — registers a callback function to be called when the form control is touched.</li><li>setDisabledState(isDisabled: boolean): void — sets the disabled state of the form control based on the provided boolean parameter.</li></ul><pre>@Component(...)<br>export class CustomInputComponent implements ControlValueAccessor {<br>  value: string;<br>  disabled = false;<br>  onChange: any = (value: any) =&gt; {};<br>  onTouched: any = () =&gt; {};<br><br>  writeValue(obj: any): void {<br>    this.value = obj;<br>  }<br><br>  registerOnChange(fn: any): void {<br>    this.onChange = fn;<br>  }<br><br>  registerOnTouched(fn: any): void {<br>    this.onTouched = fn;<br>  }<br><br>  setDisabledState(isDisabled: boolean): void {<br>    this.disabled = isDisabled;<br>  }<br>}</pre><p>5. Create template for your custom form control:</p><ul><li>In the template add the selector for your custom control component.</li><li>Bind the control to a form using ngModel, formControl, or formControlName directives as you would with any other form control.</li></ul><pre>&lt;input<br>  type=&quot;text&quot;<br>  [(ngModel)]=&quot;value&quot;<br>  [disabled]=&quot;disabled&quot;<br>  (input)=&quot;onChange(value)&quot;<br>  (blur)=&quot;onTouched()&quot;<br>/&gt;</pre><p>6. Use the custom form control:</p><ul><li>Create a form where you want to use a custom form control.</li></ul><pre>@Component(...)<br>export class AppComponent {<br>  form = new FormGroup({<br>    name: new FormControl(&#39;&#39;),<br>  });<br>}</pre><ul><li>Include custom control component to your form in the template.</li></ul><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>  &lt;app-custom-input formControlName=&quot;name&quot;&gt;&lt;/app-custom-input&gt;<br>&lt;/form&gt;</pre><h4><strong>Custom validators</strong></h4><p>Here’s an example of how to add validators to the custom control component 👇</p><p>1. In the component’s TypeScript file, implement the Validator interface.</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;;<br>import { <br>  ControlValueAccessor, <br>  NG_VALUE_ACCESSOR, <br>  Validator <br>} from &#39;@angular/forms&#39;;<br><br>@Component(...)<br>export class CustomInputComponent implements ControlValueAccessor, Validator {}</pre><p>2. Provide the NG_VALIDATORS token and set it to use the forwardRef function to reference your custom control.</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;<br>import {<br>  ControlValueAccessor,<br>  NG_VALUE_ACCESSOR,<br>  Validator,<br>  NG_VALIDATORS<br>} from &#39;@angular/forms&#39;<br><br>@Component({<br>  selector: &#39;app-custom-input&#39;,<br>  templateUrl: &#39;./custom-input.component.html&#39;,<br>  styleUrls: [&#39;./custom-input.component.css&#39;],<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; CustomInputComponent),<br>      multi: true<br>    },<br>    {<br>      provide: NG_VALIDATORS,<br>      useExisting: forwardRef(() =&gt; CustomInputComponent),<br>      multi: true<br>    }<br>  ]<br>})<br>export class CustomInputComponent implements ControlValueAccessor, Validator {}</pre><p>3. Implement the validate method to custom control component.</p><p>The validate method is where you can perform your custom validation logic. By returning ValidationErrors object with specific keys and values, you can provide custom validation error messages for the form control. If there are no validation errors, returning null indicates that the control is considered valid.</p><pre>validate(control: AbstractControl): ValidationErrors | null {<br>    // Perform validation logic here<br>    if (!control.value || control.value === &#39;&#39;) {<br>      return { required: true };<br>    }<br>    return null;<br>}</pre><p>4. Update the form control in the parent component’s template to include the validator:</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>  &lt;app-custom-input formControlName=&quot;name&quot;&gt;&lt;/app-custom-input&gt;<br>  &lt;div *ngIf=&quot;form.controls.name.invalid &amp;&amp; form.controls.name.touched&quot;&gt;<br>    &lt;span *ngIf=&quot;form.controls.name.errors?.required&quot;<br>      &gt;This field is required&lt;/span<br>    &gt;<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><h4><strong>Conclusion</strong></h4><p>In conclusion, creating custom form controls in Angular allows developers to make forms that are personalized to their specific needs and design choices. By understanding how Angular’s Reactive Forms module works and utilizing its component-based approach, you now have the ability to build custom controls that are both functional and visually appealing for your applications.</p><h4><strong>Wrapping up</strong></h4><p>I hope that thanks to this article you will now know how to create custom form control in Angular. If you want to see the whole example, you can do it here on <a href="https://stackblitz.com/edit/create-custom-form-control">StackBlitz ⚡️</a>.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd98213d06c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/custom-form-control-in-angular-8bd98213d06c">Custom Form Control in Angular 🙌</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart & Dumb Components in Angular ]]></title>
            <link>https://medium.com/@sniadek97/smart-dumb-components-in-angular-c11e43ed312e?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11e43ed312e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 04:01:43 GMT</pubDate>
            <atom:updated>2023-03-27T04:01:43.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WkfaN5es668okb2F" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Components are the building blocks of Angular applications. They are responsible for managing the UI and the behavior of a specific part of the application. Components can be categorized into two types according to their responsibilities: Smart Components and Dumb Components.</p><h4><strong>Dumb components</strong></h4><p>Dumb components focuses only on rendering the user interface and receiving input/output data from the parent component. They do not perform any business logic nor interact with services. Typically, dumb components receive data through input bindings and emit events through output bindings, which are used to communicate with the parent component.</p><p>Below is an example of creating and using a Dumb component in Angular.</p><pre>@Component({<br>  selector: &#39;app-shopping-list&#39;,<br>  templateUrl: &#39;./shopping-list.component.html&#39;,<br>  styleUrls: [&#39;./shopping-list.component.css&#39;],<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class ShoppingListComponent {<br>  @Input() list: { id: number, value: string }[]<br>}</pre><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let item of list&quot;&gt;{{ item.value }}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>As you can see, the component takes a list variable as an @Input() and displays it to the user as a list of items. The list is passed from the parent component, where communication with the service takes place.</p><h4><strong>Smart components</strong></h4><p>Smart components manage logic, state, and data processing in an application. This type of component holds business logic and handles communication between other components. Smart components often interact with services and APIs, and control the flow of data. They are also responsible for handling user events and rendering the appropriate view to the user.</p><p>Below is an example of a Smart component that is the parent component for the above example using a Dumb component.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br>export class AppComponent {<br>  shoppingList$: Observable&lt;{ id: number; value: string }[]&gt;;<br><br>  constructor(private _shoppingService: ShoppingService) {<br>    this.shoppingList$ = this._shoppingService.getShoppingList();<br>  }<br>}</pre><pre>&lt;app-shopping-list [list]=&quot;shoppingList$ | async&quot;&gt;&lt;/app-shopping-list&gt;</pre><p>As we can see, a service is injected into the component, which allows us to retrieve a list that we pass to the child component.</p><p>The example shows us that the Smart component communicates with the service, while the Dumb component is only used to display the result that is passed to it by the parent component. The separation of Smart and Dumb components helps to keep the code organized and makes it easier to maintain. Thanks to this, we can reuse components throughout the project.</p><h4><strong>Wrapping up</strong></h4><p>I hope that thanks to this article you will understand the important role that Smart and Dumb components play in applications. If you want to see the whole example, you can do it here on <a href="https://stackblitz.com/edit/smart-and-dumb-components">StackBlitz ⚡</a>️.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11e43ed312e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom operators in RxJS ‍‍]]></title>
            <link>https://medium.com/@sniadek97/custom-operators-in-rxjs-717dbdc5eb6f?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/717dbdc5eb6f</guid>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 06:02:07 GMT</pubDate>
            <atom:updated>2023-03-17T06:02:07.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xa6jV1d7e6dpv4zX" /><figcaption>Photo by <a href="https://unsplash.com/@nikhilmitra?utm_source=medium&amp;utm_medium=referral">Nikhil Mitra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most programmers try to keep their code as DRY (Don’t Repeat Yourself) as possible, as it is a good practice to maintain clean code. But what do RxJS operators have to do with it? Let’s find out 👀</p><p>When working with observables, we may encounter a lot of repetitive code. But there’s no need to worry because RxJS provides a way to create custom operators. Some examples are given below 👇</p><h4><strong>Operator for Handling Input Events</strong></h4><p>In this example, we will create a custom RxJS operator using the pipe method. Let’s imagine that in our project, we have many listeners for changes in input values. In such situations, we often use operators such as debounceTime and distinctUntilChanged. Thanks to the ability to create custom operators, we can combine these two operators into one and avoid repeating them every time.</p><p>Check out the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c9fcf4613b97ea275b5dbfb23ab90f8/href">https://medium.com/media/4c9fcf4613b97ea275b5dbfb23ab90f8/href</a></iframe><p>The debounceTime operator delays the emission of values from the source Observable by a specified amount of time and emits the latest value emitted during that time window.</p><p>On the other hand, the distinctUntilChanged operator filters out values that are the same as the previous value emitted by the source Observable.</p><p>Together, these operators provide a useful combination for handling input events. They enable you to wait until the user has finished typing before performing an expensive operation, and you only want to process each unique event once.</p><p>Here’s an example of how you can use these operators.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e77174ef31320dca4a2cfbf6affba1f/href">https://medium.com/media/7e77174ef31320dca4a2cfbf6affba1f/href</a></iframe><p>And that’s it! With the valueChangesOperator, you no longer need to repeat the same code repeatedly 🙌</p><h4><strong>Operator for Handling HTTP Requests</strong></h4><p>You can also create more advanced operators. For instance, if we handle HTTP requests in a similar way in most cases, we can create our custom operator for that too.</p><p>Let’s assume that in our application, we want to display a message when an HTTP request succeeds or an error occurs. Additionally, we always use the takeUntil operator to unsubscribe, and we want to display a loader when sending a request. Once the request is completed, we want to hide the loader.</p><p>Our custom RxJS operator for this and the example of using it looks as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9bcc354a947280e17ecf44e2f05076e/href">https://medium.com/media/f9bcc354a947280e17ecf44e2f05076e/href</a></iframe><p>This function is a custom RxJS operator that returns a MonoTypeOperatorFunction&lt;T&gt;. It creates a pipeline of operators that can be applied to an input Observable, including tap, catchError, finalize, and takeUntil.</p><p>The tap operator is used to display a success message.</p><p>The catchError operator catches any errors emitted by the input Observable and handles them by displaying an error message and returning a new Observable that emits the error using the throwError function.</p><p>The finalize operator performs a side-effect when the input Observable completes or errors, in this case setting a loading state to false.</p><p>The takeUntil operator completes the output Observable when a specified Observable (this.destroy$) emits a value. This is useful for unsubscribe when a component is destroyed.</p><p>This operator has side effects, so it must be created within the component. If you want to use such an operator in multiple components, you need to modify it and remove the side effects.</p><h4>Wrapping up</h4><p>The examples above demonstrate how you can create your own RxJS operators, and you can customize them to meet your specific needs. I hope this article was helpful and thanks to this you will be able to create your own operators. If you want to test the above code, you can do it here on <a href="https://stackblitz.com/edit/angular-custom-rxjs-operators">StackBlitz ⚡️</a>.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717dbdc5eb6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize your Angular app with trackBy ]]></title>
            <link>https://blog.devgenius.io/optimize-your-angular-app-with-trackby-dfcd82b2031c?source=rss-2928654bf9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfcd82b2031c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ania Sniadek ⚡️]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 07:53:17 GMT</pubDate>
            <atom:updated>2023-09-26T16:58:33.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*duWnw3L7o8qBDOjp" /><figcaption>Photo by Tech Daily on Unsplash</figcaption></figure><p>Most of us create a list of elements using the ngFor directive in our Angular applications. But do you know how much it can affect our application&#39;s performance? If you want to find out, take a look below ⬇️</p><p>When we use the ngFor directive to create a list of elements and want to change or modify some of them, Angular needs to re-render all nodes in the DOM. This could be a very heavy operation, especially if we have large data collections that frequently change. These changes could significantly impact our application&#39;s performance 👀</p><h4><strong>Solution 💡</strong></h4><p>We can improve our app’s performance by adding the trackBy directive to our ngFor. The trackBy directive allows us to provide a function that returns a unique identifier for each item in the array. This function takes an index and a given element as arguments.</p><p>Thanks to this feature, when we change a given list, Angular can track changes to the array and update the DOM only for the items that have a new identifier. Therefore, the change occurs only in that particular element rather than in all DOM elements 🙌</p><h4><strong>How to add trackBy❓</strong></h4><p>Let’s create an example with a simple list to show you how to add a trackBy directive to your application.</p><p>First, create a component with an array of items and our trackBy function.</p><pre>@Component(...)<br>export class AppComponent {<br>  items: { id: number, name: string }[] = [<br>    { id: 1, name: &#39;Item 1&#39; },<br>    { id: 2, name: &#39;Item 2&#39; },<br>    { id: 3, name: &#39;Item 3&#39; }<br>  ];<br><br>  trackByFn(index: number, item: { id: number, name: string }): number {<br>    return item.id;<br>  }<br>}</pre><p>Here, we need to return a unique identifier for each item. In this case, we use the id of the item. If the item has no id or any unique key, we can just return the index.</p><p>Now, simply create a list in our HTML file and use trackByFn. See the code below 👇</p><pre>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let item of items; trackBy: trackByFn&quot;&gt;{{ item.name }}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>With the trackBy directive, the ngFor directive can track elements, and Angular can perform unique updates in our DOM 🤩</p><h4><strong>Wrapping up</strong></h4><p>The above example is straightforward, so there will be no slowdown in the application. However, imagine having a very large collection of data that frequently change. In such cases, adding the trackBy directive could be very useful.</p><p>If you’ve enjoyed reading this, please give a few claps 👏 . Feel free to follow me and to leave a comment with your feedback 👇.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfcd82b2031c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/optimize-your-angular-app-with-trackby-dfcd82b2031c">Optimize your Angular app with trackBy 🦾</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>