<?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 Volodymyr Chykharivskyi on Medium]]></title>
        <description><![CDATA[Stories by Volodymyr Chykharivskyi on Medium]]></description>
        <link>https://medium.com/@v.chykharivskyi?source=rss-1f565df4dc13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FyfzWtW9mVqXOSDB</url>
            <title>Stories by Volodymyr Chykharivskyi on Medium</title>
            <link>https://medium.com/@v.chykharivskyi?source=rss-1f565df4dc13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:37:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@v.chykharivskyi/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[Angular Action Handling Made Easy: A Guide to Clean Code with Dependency Injection]]></title>
            <link>https://medium.com/@v.chykharivskyi/angular-action-handling-made-easy-a-guide-to-clean-code-with-dependency-injection-9d192841d211?source=rss-1f565df4dc13------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d192841d211</guid>
            <category><![CDATA[angular-actions-with-di]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[action-handling]]></category>
            <dc:creator><![CDATA[Volodymyr Chykharivskyi]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 11:53:25 GMT</pubDate>
            <atom:updated>2024-11-07T12:00:12.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALJhJJBW-hRyEObqZHpY7w.png" /><figcaption>Image Source: <a href="https://ionic.io/blog/wp-content/uploads/2024/02/angular-feature-image-1.png">ionic.io</a></figcaption></figure><h3>Introduction</h3><p>In Angular applications, handling actions (like renaming, deleting, and more) directly in each component often leads to repetitive, hard-to-maintain code. Each component ends up with its own logic for these actions, creating duplication and making it difficult to keep behavior consistent.</p><p>This article introduces a better approach: using dependency injection (DI) to centralize action handling in a shared service. With DI, we can manage actions from a single place, making components simpler and reducing code duplication. We’ll look at an example with a list view and a detailed view — each requiring different action handling — to see how DI keeps our code clean, organized, and easy to maintain.</p><h4>Key Concepts and Technologies</h4><p>Before diving into the code, let’s go over a few key concepts and technologies that are foundational to this approach:</p><ul><li><a href="https://angular.dev/guide/di"><strong>Dependency Injection (DI)</strong></a>: Angular’s DI system allows components and services to inject instances of other classes, promoting reusability and reducing coupling. We use DI to centralize action handling in an ActionService, keeping components lightweight and focused on the UI.</li><li><a href="https://rxjs.dev/"><strong>RxJS</strong></a>: RxJS is a library for reactive programming with Observables. Here, we use <a href="https://rxjs.dev/api/index/class/Subject">Subject</a> from RxJS to handle action streams, enabling components to react to actions as they occur. This also simplifies memory management and subscription handling.</li></ul><h3>Problem Statement</h3><p>Consider a scenario where we have a list view of users (UserListComponent) and a detailed user view (UserViewComponent). Each view needs to handle actions like rename or delete, but the logic for these actions varies between views. Typically, actions are handled directly within components, which can result in redundant code and tightly coupled components.</p><p>Here’s the traditional approach where each component directly manages actions like onDelete and onRename:</p><pre>import { Component, output } from &#39;@angular/core&#39;;<br><br>@Component({<br>    selector: &#39;app-user-list&#39;,<br>    standalone: true,<br>    imports: [UserCardComponent],<br>    template: `<br>         &lt;app-user-card (delete)=&quot;onDelete()&quot; (rename)=&quot;onRename($event)&quot; /&gt;<br>    `,<br>})<br>export class UserListComponent {<br>    public onDelete(): void {<br>        // handle delete<br>    }<br>  <br>    public onRename(_user: User): void {<br>        // handle rename<br>    }<br>}<br><br>// ----------------------------------- User card ---------------------------------------<br><br>@Component({<br>    selector: &#39;app-user-card&#39;,<br>    standalone: true,<br>    imports: [UserActionComponent],<br>    template: `<br>         &lt;app-user-action (delete)=&quot;onDelete()&quot; (rename)=&quot;onRename($event)&quot; /&gt;<br>    `,<br>})<br>export class UserCardComponent {<br>     public readonly rename = output&lt;User&gt;();<br>     public readonly delete = output();<br>    <br>     public onDelete(): void {<br>          this.delete.emit();<br>     }<br>    <br>     public onRename(user: User): void {<br>          this.rename.emit(user);<br>     }<br>}<br><br>// ----------------------------------- User actions ------------------------------------<br><br>@Component({<br>    selector: &#39;app-user-action&#39;,<br>    standalone: true,<br>    template: `<br>         &lt;button (click)=&quot;onRenameClick()&quot;&gt;Rename&lt;/button&gt;<br>         &lt;button (click)=&quot;onDeleteClick()&quot;&gt;Delete&lt;/button&gt;<br>    `,<br>})<br>export class UserActionComponent {<br>     public readonly rename = output&lt;User&gt;();<br>     public readonly delete = output();<br>    <br>     public onDeleteClick(): void {<br>          this.delete.emit();<br>     }<br>    <br>     public onRenameClick(): void {<br>          this.rename.emit({ id: 1, name: &#39;new name&#39; });<br>     }<br>}<br><br>// ----------------------------------- User view ---------------------------------------<br><br>@Component({<br>     selector: &#39;app-user-view&#39;,<br>     standalone: true,<br>     imports: [UserActionsComponent],<br>     template: `&lt;app-user-actions (delete)=&quot;onDelete()&quot; (rename)=&quot;onRename($event)&quot; /&gt;`,<br>})<br>export class UserViewComponent {<br>    public onDelete(): void {<br>        // handle delete<br>    }<br>  <br>    public onRename(_user: User): void {<br>        // handle rename<br>    }<br>}</pre><h3>The Dependency Injection Solution</h3><p>Using dependency injection, we can delegate action handling to a shared service, which each component can inject as needed. This allows for centralized management of actions while keeping the components themselves lightweight and focused on the view.</p><p>Here’s how we can organize it:</p><h4>Step 1: Define an Action Interface</h4><p>Define a common interface for actions with different types to ensure type safety and flexibility as the app grows.</p><pre>export interface Action {<br>    type: string;<br>}<br><br>export interface UserDeleteAction extends Action {<br>    type: &#39;delete&#39;;<br>}<br><br>export interface UserRenameAction extends Action {<br>    type: &#39;rename&#39;;<br>    user: User;<br>}<br><br>export type UserActions = UserDeleteAction | UserRenameAction;</pre><h4>Step 2: Create the Action Service</h4><p>The ActionService will be a singleton service that uses Subject to emit actions. Components can inject this service and subscribe to actions, centralizing action handling logic.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Subject } from &#39;rxjs&#39;;<br><br>@Injectable()<br>export class ActionService&lt;T extends Action&gt; {<br>    public readonly action$ = new Subject&lt;T&gt;();<br>}</pre><h4>Step 3: Action Component with DI for Emitting Actions</h4><p>The UserActionsComponent emits actions like rename and delete by pushing them to the ActionService, which other components can listen to. Dependency injection is used to access ActionService as needed.</p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-user-actions&#39;,<br>  standalone: true,<br>  template: `<br>      &lt;button (click)=&quot;onRenameClick()&quot;&gt;Rename&lt;/button&gt;<br>      &lt;button (click)=&quot;onDeleteClick()&quot;&gt;Delete&lt;/button&gt;<br>  `,<br>})<br>export class UserActionsComponent {<br>    private readonly actionService = inject&lt;ActionService&lt;UserActions&gt;&gt;(ActionService, { optional: true });<br>  <br>    public onDeleteClick(): void {<br>        this.actionService?.action$.next({ type: &#39;delete&#39; });<br>    }<br>  <br>    public onRenameClick(): void {<br>        this.actionService?.action$.next({ type: &#39;rename&#39;, user: { id: 1, name: &#39;new name&#39; } });<br>    }<br>}</pre><h4><strong>Step 4: List and View Components with DI for Action Handling</strong></h4><p>The UserListComponent and UserViewComponent now inject ActionService to handle actions. Here, we add custom logic in each component to handle actions differently, such as logging actions in UserListComponent and updating details in UserViewComponent.</p><pre>import { Component, inject, OnDestroy, OnInit } from &#39;@angular/core&#39;;<br>import { Subscription } from &#39;rxjs&#39;;<br><br>@Component({<br>    selector: &#39;app-user-list&#39;,<br>    standalone: true,<br>    imports: [UserCardComponent],<br>    template: `<br>       &lt;app-user-card /&gt;<br>    `,<br>    providers: [ActionService],<br>})<br>export class UserListComponent implements OnInit, OnDestroy {<br>    private subscription!: Subscription;<br>    private readonly actionService = inject&lt;ActionService&lt;UserActions&gt;&gt;(ActionService);<br>  <br>    public ngOnInit(): void {<br>        this.subscription = this.actionService.action$.subscribe(action =&gt; this.onAction(action));<br>    }<br>  <br>    public ngOnDestroy(): void {<br>        this.subscription.unsubscribe();<br>    }<br>  <br>    private onAction(action: UserActions): void {<br>        switch (action.type) {<br>          case &#39;rename&#39;:<br>              // handle rename logic for list view<br>              break;<br>          case &#39;delete&#39;:<br>              // handle delete logic for list view<br>              break;<br>          default:<br>              // handle default case<br>        }<br>    }<br>}<br><br>// ----------------------------------- User view ------------------------------------------<br><br>@Component({<br>     selector: &#39;app-user-view&#39;,<br>     standalone: true,<br>     imports: [UserActionsComponent],<br>     template: `&lt;app-user-actions /&gt;`,<br>     providers: [ActionService],<br>})<br>export class UserViewComponent implements OnInit, OnDestroy {<br>    private subscription!: Subscription;<br>    private readonly actionService = inject&lt;ActionService&lt;UserActions&gt;&gt;(ActionService);<br>  <br>    public ngOnInit(): void {<br>        this.subscription = this.actionService.action$.subscribe(action =&gt; this.onAction(action));<br>    }<br>  <br>    public ngOnDestroy(): void {<br>        this.subscription.unsubscribe();<br>    }<br>  <br>    private onAction(action: UserActions): void {<br>        switch (action.type) {<br>          case &#39;rename&#39;:<br>              // handle rename logic for list view<br>              break;<br>          case &#39;delete&#39;:<br>              // handle delete logic for list view<br>              break;<br>          default:<br>              // handle default case<br>        }<br>    }<br>}</pre><h3>Benefits of This Approach</h3><ul><li><strong>Code Reusability</strong>: The centralized service allows action handling to be shared across components without duplicating code.</li><li><strong>Decoupling Components</strong>: Components no longer need to define their own handlers, reducing complexity and making them more focused on rendering views.</li><li><strong>Enhanced Maintainability</strong>: Changes to action handling logic can be made in one place, in the service, without modifying multiple components.</li></ul><h3>Conclusion</h3><p>By centralizing action handling with dependency injection, we enhance modularity and reduce redundancy. This setup is particularly beneficial in larger applications where multiple views share common actions but may require different handling. Using DI for action management creates a scalable, maintainable solution that grows with your application’s complexity, making Angular action handling simpler, cleaner, and more robust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d192841d211" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Duplicating Code: Create a Single Control in Angular for All Your Selection Needs (Radio…]]></title>
            <link>https://medium.com/tenantcloud-engineering/stop-duplicating-code-create-a-single-control-in-angular-for-all-your-selection-needs-radio-4e12b6f1a545?source=rss-1f565df4dc13------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e12b6f1a545</guid>
            <category><![CDATA[form-controls]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[checkbox]]></category>
            <category><![CDATA[angular-components]]></category>
            <category><![CDATA[radiobutton]]></category>
            <dc:creator><![CDATA[Volodymyr Chykharivskyi]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 13:02:50 GMT</pubDate>
            <atom:updated>2024-11-08T18:22:13.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Duplicating Code: Create a Single Control in Angular for All Your Selection Needs (Radio, Checkbox, and More)</h3><figure><img alt="Create a Single Control in Angular for All Your Selection Needs (Radio, Checkbox, and More)" src="https://cdn-images-1.medium.com/max/1024/1*B3wkfGlsm8xWjpT1VewHgQ.png" /><figcaption>Image Source: <a href="https://ionic.io/blog/wp-content/uploads/2024/02/angular-feature-image-1.png">ionic.io</a></figcaption></figure><h3>Introduction</h3><p>Selection controls, such as radio buttons and checkboxes, are common elements in user interfaces. Often, developers need to replicate similar logic for managing single and multiple selections across different UI components. This approach, however, can lead to duplicated code and increased maintenance.</p><p>In this article, we’ll create a reusable control in Angular that handles both single and multiple selections. By centralizing the logic, we’ll simplify the UI management and allow the control to handle different use cases, such as radio buttons, checkboxes, and any custom choice components.</p><h4>Key Concepts and Technologies</h4><p>To build a reusable selection control in Angular, we’ll be using several key concepts and technologies:</p><ul><li><a href="https://material.angular.io/cdk/collections/overview">SelectionModel</a>: Manages selection state for single or multiple items, simplifying selection tracking within a group.</li><li><a href="https://angular.dev/api/forms/ControlValueAccessor?tab=api">ControlValueAccessor</a>: Integrates our custom component with Angular forms, making it compatible with reactive and template-driven forms.</li><li><a href="https://rxjs.dev/">RxJS</a>: Used to handle reactive streams and manage memory effectively, enhancing the component’s reactivity and performance.</li><li><a href="https://www.youtube.com/watch?v=2rQOu9TmuxE&amp;ab_channel=DecodedFrontend">Bridge Pattern</a>: This pattern facilitates communication between child and parent components, enabling ChoiceGroupComponent to manage group-wide selection state while ChoiceItemDirective handles the behavior of individual items independently.</li></ul><h3>Setting Up the Choice Group Component</h3><p>The ChoiceGroupComponent serves as the primary controller for managing selection. It consolidates the selection logic for any choice component (e.g., radio or checkbox), tracks selected options, and updates the UI as choices are made.</p><pre>import {<br>    AfterContentInit,<br>    ChangeDetectionStrategy,<br>    Component,<br>    computed,<br>    ContentChildren, DestroyRef, inject,<br>    input,<br>    InputSignal,<br>    QueryList,<br>    Signal,<br>} from &#39;@angular/core&#39;;<br>import { SelectionModel } from &#39;@angular/cdk/collections&#39;;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;<br>import { merge } from &#39;rxjs&#39;;<br>import { takeUntilDestroyed } from &quot;@angular/core/rxjs-interop&quot;;<br>import { startWith, switchMap, tap } from &#39;rxjs/operators&#39;;<br><br>import { ChoiceItemDirective } from &#39;../../directives/choice-item/choice-item.directive&#39;;<br><br>export type ChoiceKey = string | number | boolean;<br><br>export abstract class ChoiceGroup&lt;Key extends ChoiceKey = ChoiceKey&gt; {<br>    public abstract name: InputSignal&lt;string&gt;;<br><br>    public abstract isMultipleMode: Signal&lt;boolean&gt;;<br><br>    public abstract onChoiceChange(key: Key): void;<br>    public abstract triggerContentChildrenChanges(): void;<br>}<br><br>export abstract class SelectionStrategy&lt;Key&gt; {<br>    public abstract getValue(selectionModel: SelectionModel&lt;Key&gt;): null | Key | Key[];<br><br>    public abstract changeSelection(selectionModel: SelectionModel&lt;Key&gt;, key: Key): boolean;<br>}<br><br>export class SingleSelectionStrategy&lt;Key&gt; extends SelectionStrategy&lt;Key&gt; {<br>    public getValue(selectionModel: SelectionModel&lt;Key&gt;): Key | null {<br>        return selectionModel.isEmpty() ? null : selectionModel.selected[0];<br>    }<br><br>    public changeSelection(selectionModel: SelectionModel&lt;Key&gt;, key: Key): boolean {<br>        if (selectionModel.isSelected(key)) return false;<br><br>        selectionModel.select(key);<br>        return true;<br>    }<br>}<br><br>export class ToggleableSingleSelectionStrategy&lt;Key&gt; extends SelectionStrategy&lt;Key&gt; {<br>    public getValue(selectionModel: SelectionModel&lt;Key&gt;): Key | null {<br>        return selectionModel.isEmpty() ? null : selectionModel.selected[0];<br>    }<br><br>    public changeSelection(selectionModel: SelectionModel&lt;Key&gt;, key: Key): boolean {<br>        selectionModel.toggle(key);<br>        return true;<br>    }<br>}<br><br>export class MultipleSelectionStrategy&lt;Key&gt; extends SelectionStrategy&lt;Key&gt; {<br>    public getValue(selectionModel: SelectionModel&lt;Key&gt;): Key[] {<br>        return selectionModel.selected;<br>    }<br><br>    public changeSelection(selectionModel: SelectionModel&lt;Key&gt;, key: Key): boolean {<br>        selectionModel.toggle(key);<br>        return true;<br>    }<br>}<br><br>@Component({<br>    selector: &#39;choice-group&#39;,<br>    template: `&lt;ng-content&gt;&lt;/ng-content&gt;`,<br>    providers: [<br>        { provide: NG_VALUE_ACCESSOR, useExisting: ChoiceGroupComponent, multi: true },<br>        { provide: ChoiceGroup, useExisting: ChoiceGroupComponent },<br>    ],<br>    changeDetection: ChangeDetectionStrategy.OnPush,<br>    standalone: true,<br>})<br>export class ChoiceGroupComponent&lt;Key extends ChoiceKey = ChoiceKey&gt;<br>    implements ControlValueAccessor, ChoiceGroup&lt;Key&gt;, AfterContentInit {<br>    // Access all choice items within the group<br>    @ContentChildren(ChoiceItemDirective, { descendants: true }) public optionContents!: QueryList&lt;<br>        ChoiceItemDirective&lt;Key&gt;<br>    &gt;;<br><br>    public readonly name = input.required&lt;string&gt;();<br>    public readonly mode = input&lt;&#39;single&#39; | &#39;single-toggle&#39; | &#39;multiple&#39;&gt;(&#39;single&#39;);<br><br>    public readonly isMultipleMode = computed(() =&gt; &#39;multiple&#39; === this.mode());<br><br>    private readonly strategy = computed(() =&gt; this.getSelectionStrategy(this.mode()));<br>    private readonly selectionModel = computed(() =&gt; new SelectionModel&lt;Key&gt;(this.isMultipleMode()));<br><br>    private onChange!: (value: null | Key | Key[]) =&gt; void;<br>    private onTouch!: () =&gt; void;<br><br>    private disabled = false;<br><br>    private readonly optionMap = new Map&lt;Key, ChoiceItemDirective&lt;Key&gt;&gt;();<br><br>    private readonly destroyRef = inject(DestroyRef)<br><br>    public ngAfterContentInit(): void {<br>        // Subscribe to selection changes and update active state accordingly<br>        this.selectionModel().changed.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(values =&gt; {<br>            values.removed.forEach(rv =&gt; this.setIsActive(rv, false));<br>            values.added.forEach(av =&gt; this.setIsActive(av, true));<br>        });<br><br>        // Detect and handle dynamic changes in option contents<br>        this.optionContents.changes<br>            .pipe(<br>                startWith&lt;QueryList&lt;ChoiceItemDirective&lt;Key&gt;&gt;&gt;(this.optionContents),<br>                tap(() =&gt; this.refreshOptionsMap()),<br>                switchMap(options =&gt; merge(options)),<br>                takeUntilDestroyed(this.destroyRef),<br>            )<br>            .subscribe(() =&gt; {<br>                this.selectionModel().selected.forEach(key =&gt; this.setIsActive(key, true));<br><br>                // setTimeout needs for run this code after effect in ChoiceItemDirective<br>                setTimeout(() =&gt; this.updateIsDisabled(this.disabled));<br>            });<br>    }<br><br>    public writeValue(value: Key): void {<br>        this.writeModel(value);<br>    }<br><br>    public registerOnChange(fn: (value: null | Key | Key[]) =&gt; void): void {<br>        this.onChange = fn;<br>    }<br><br>    public registerOnTouched(fn: () =&gt; void): void {<br>        this.onTouch = fn;<br>    }<br><br>    public setDisabledState(isDisabled: boolean): void {<br>        this.disabled = isDisabled;<br><br>        this.updateIsDisabled(isDisabled);<br>    }<br><br>    public onChoiceChange(key: Key): void {<br>        const isChanged = this.strategy().changeSelection(this.selectionModel(), key);<br>        if (!isChanged) return; // Do nothing if no change occurred<br>    <br>        this.onChange(this.strategy().getValue(this.selectionModel()));<br>        this.onTouch();<br>    }<br><br>    public triggerContentChildrenChanges(): void {<br>        this.optionContents.notifyOnChanges();<br>    }<br><br>    private setIsActive(key: Key, isActive: boolean): void {<br>        this.optionMap.get(key)?.setIsActive(isActive);<br>    }<br><br>    private updateIsDisabled(isDisabled: boolean): void {<br>        this.optionContents?.forEach(option =&gt; option.setIsDisabled(isDisabled));<br>    }<br><br>    private refreshOptionsMap(): void {<br>        this.optionMap.clear();<br>        this.optionContents.forEach(choice =&gt; this.optionMap.set(choice.key(), choice));<br>    }<br><br>    private writeModel(value: null | Key | Key[]): void {<br>        this.selectionModel().clear();<br><br>        if (value === null || value === undefined) return;<br><br>        Array.isArray(value) ? this.selectionModel().select(...value) : this.selectionModel().select(value);<br>    }<br><br>    private getSelectionStrategy(mode: &#39;single&#39; | &#39;single-toggle&#39; | &#39;multiple&#39;): SelectionStrategy&lt;Key&gt; {<br>        switch (mode) {<br>            case &#39;single&#39;:<br>                return new SingleSelectionStrategy&lt;Key&gt;();<br>            case &#39;single-toggle&#39;:<br>                return new ToggleableSingleSelectionStrategy&lt;Key&gt;();<br>            case &#39;multiple&#39;:<br>                return new MultipleSelectionStrategy&lt;Key&gt;();<br>            default:<br>                throw new Error(`Unsupported mode: ${mode}`);<br>        }<br>    }<br>}</pre><h3>ChoiceItemDirective: Flexible UI with Individual Choice Items</h3><p>ChoiceItemDirective encapsulates the behavior of each choice item, providing properties like isActive and isDisabled. It notifies ChoiceGroupComponent of changes, updating the selection state.</p><pre>import { Directive, effect, HostListener, input, signal } from &#39;@angular/core&#39;;<br>import { takeUntilDestroyed, toObservable } from &#39;@angular/core/rxjs-interop&#39;;<br>import { skip } from &#39;rxjs/operators&#39;;<br><br>import { ChoiceGroup, ChoiceKey } from &quot;../../components/choice-group/choice-group.component&quot;;<br><br>@Directive({<br>    standalone: true,<br>    selector: &#39;choice-item, [choiceItem]&#39;,<br>    host: { &#39;[class.active]&#39;: &#39;isActive()&#39;, &#39;[class.disabled]&#39;: &#39;isDisabled()&#39; },<br>})<br>export class ChoiceItemDirective&lt;Key extends ChoiceKey = ChoiceKey&gt; {<br>    public readonly key = input.required&lt;Key&gt;();<br>    public readonly disabled = input(false);<br><br>    public readonly isDisabled = signal(false);<br>    public readonly isActive = signal(false);<br><br>    constructor(private readonly choiceGroup: ChoiceGroup) {<br>        effect(() =&gt; this.setIsDisabled(this.disabled()), { allowSignalWrites: true });<br><br>        effect(() =&gt; {<br>            if (this.key() === null || this.key() === undefined) throw new Error(`[choice-item] Every item should have key`);<br>        });<br><br>        toObservable(this.key)<br>            .pipe(skip(1), takeUntilDestroyed())<br>            .subscribe(() =&gt; this.choiceGroup.triggerContentChildrenChanges());<br>    }<br><br>    public setIsActive(value: boolean): void {<br>        this.isActive.set(value);<br>    }<br><br>    public setIsDisabled(value: boolean): void {<br>        this.isDisabled.set(value || this.disabled());<br>    }<br><br>    @HostListener(&#39;click&#39;, [&#39;$event&#39;])<br>    public onHostClick(event: Event): void {<br>        event.preventDefault();<br>        event.stopPropagation();<br><br>        if (this.isDisabled()) return;<br><br>        this.choiceGroup.onChoiceChange(this.key());<br>    }<br>}</pre><h3>Adding ChoiceItemWrapperComponent for Semantic HTML</h3><p>The ChoiceItemWrapperComponent was introduced to ensure that the selection control produces semantic and accessible HTML. By wrapping each choice item, this component enforces a standard structure for radio buttons and checkboxes, pairing each &lt;input&gt; element with a &lt;label&gt;. This structure improves accessibility and makes the component more user-friendly for screen readers.</p><pre>import { ChangeDetectionStrategy, Component, computed, inject, input } from &#39;@angular/core&#39;;<br><br>import { ChoiceItemDirective } from &#39;../../directives/choice-item/choice-item.directive&#39;;<br><br>import { ChoiceGroup, ChoiceKey } from &#39;../choice-group/choice-group.component&#39;;<br><br>@Component({<br>    selector: &#39;choice-item-wrapper&#39;,<br>    `,<br>    template: `<br>        &lt;input<br>            [checked]=&quot;choiceItemDirective.isActive()&quot;<br>            [disabled]=&quot;choiceItemDirective.isDisabled()&quot;<br>            [id]=&quot;id()&quot;<br>            [name]=&quot;name()&quot;<br>            [type]=&quot;type()&quot;<br>            [value]=&quot;choiceItemDirective.key()&quot;<br>        /&gt;<br>        &lt;label [for]=&quot;id&quot;&gt;<br>            &lt;ng-content&gt;&lt;/ng-content&gt;<br>        &lt;/label&gt;<br>    `,<br>    changeDetection: ChangeDetectionStrategy.OnPush,<br>    standalone: true,<br>})<br>export class ChoiceItemWrapperComponent&lt;Key extends ChoiceKey = ChoiceKey&gt; {<br>    public readonly type = input&lt;&#39;radio&#39; | &#39;checkbox&#39;&gt;(&#39;radio&#39;);<br><br>    public readonly choiceItemDirective = inject(ChoiceItemDirective&lt;Key&gt;);<br>    public readonly choiceGroup = inject(ChoiceGroup&lt;Key&gt;);<br><br>    // Generate unique IDs and names based on choice group properties<br>    public readonly id = computed(() =&gt; this.getItemId(this.choiceItemDirective.key()));<br>    public readonly name = computed(() =&gt; this.getItemName(this.id()));<br><br>    private getItemName(id: string): string {<br>        return this.choiceGroup.isMultipleMode() ? id : this.choiceGroup.name();<br>    }<br><br>    private getItemId(key: Key): string {<br>        return `${this.choiceGroup.name()}-${key}`;<br>    }<br>}</pre><h3>Usage Example: Creating Custom Choice Components</h3><p>The ChoiceItemWrapperComponent and ChoiceItemDirective allow you to build reusable and accessible selection components. Here, we&#39;ll demonstrate how to create a custom radio button component, RadioPointComponent, that leverages these foundational components to provide semantic HTML structure and accessibility.</p><p>By combining ChoiceItemWrapperComponent and ChoiceItemDirective, you can build other custom choice components (like checkboxes or radio cards) that are easily reusable and follow consistent HTML structure.</p><h4>Creating the RadioPointComponent</h4><pre>import { ChangeDetectionStrategy, Component } from &#39;@angular/core&#39;;<br><br>import { ChoiceItemWrapperComponent } from &quot;../../choice/components/choice-item-wrapper/choice-item-wrapper.component&quot;;<br>import { ChoiceItemDirective } from &quot;../../choice/directives/choice-item/choice-item.directive&quot;;<br><br>@Component({<br>    selector: &#39;radio-point&#39;,<br>    template: `<br>        &lt;choice-item-wrapper&gt;<br>            &lt;ng-content&gt;&lt;/ng-content&gt;<br>        &lt;/choice-item-wrapper&gt;<br>    `,<br>    changeDetection: ChangeDetectionStrategy.OnPush,<br>    standalone: true,<br>    imports: [ChoiceItemWrapperComponent],<br>    hostDirectives: [{ directive: ChoiceItemDirective, inputs: [&#39;key&#39;, &#39;disabled&#39;] }],<br>})<br>export class RadioPointComponent {}</pre><h4>Using RadioPointComponent in the Template</h4><p>To use RadioPointComponent within a ChoiceGroupComponent, simply define it in your HTML template. Here’s the full HTML structure for setting up a group of radio buttons using ChoiceGroupComponent:</p><pre>&lt;choice-group name=&quot;radio&quot; [formControl]=&quot;radioControl&quot;&gt;<br>    &lt;radio-point key=&quot;first&quot;&gt;First&lt;/radio-point&gt;<br>    &lt;radio-point key=&quot;second&quot;&gt;Second&lt;/radio-point&gt;<br>&lt;/choice-group&gt;</pre><h3>Conclusion</h3><p>This universal control centralizes selection logic, reducing duplication and improving maintainability. By using a modular approach, we created a reusable selection control that simplifies maintenance and enhances UI flexibility across multiple choice components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e12b6f1a545" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tenantcloud-engineering/stop-duplicating-code-create-a-single-control-in-angular-for-all-your-selection-needs-radio-4e12b6f1a545">Stop Duplicating Code: Create a Single Control in Angular for All Your Selection Needs (Radio…</a> was originally published in <a href="https://medium.com/tenantcloud-engineering">tenantcloud-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>