ng-generic-radio image

Radio UI Design Pattern In Angular

Vinit Tomar
2 min readNov 10, 2019

While working on frontend, I have many times encountered same scenario where I have to create UX like radio, we have in HTML.

For example we may have a paragraph and we give user a choice to align text as they like. Or we want have multiple themes and we want user to choose a theme from the available options.

Overview

If we look at functionality we require a radio-group , which will contain our options inside it and radio-option for allowing the user to make a choice. Every radio-option can be selected and unselected on the basis of user choice, and it can be disabled if developer wants to disable any option. Every option also require a unique value to distinguish from other options.

To help frontend developer I have publish a package ng-generic-radio at npm. This package has two angular component, ng-generic-radio-group and ng-generic-radio-option to help us implementing this feature.

Abstraction of Functionality for “ng-generic-radio-option”

If we look at the functionality we have three state of toggle

  • Selected state
  • Unselected state
  • Disabled state

From the above we can see that for every state we need a different view. With ng-generic-radio-option we can provide selected and unselected state’s html, disabled state will be handled automatically.

For providing selected state we have to use *selectedState directive and for unselected state we have to provide *unSelectedState directive at the parent tag for the respective state’s html.

ng-generic-radio is fully compatible with both reactive and template driven forms and developer can do everything which can be done with any other form including validations.

If you want to check the code, please go to the end of this article for demo, or you can follow step by step guide.

How to use ng-generic-radio

Below are the steps to use ng-generic-radio:

  1. npm install — save ng-generic-radio
  2. Import ng-generic-radio module in the module of component where we want to use it.
import { NgGenericRadioModule } from 'ng-generic-radio';  @NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
NgGenericRadioModule,
FormsModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }

3. Add the following lines with the required modification

3.1 html file

<ng-generic-radio-group [formControl]="demoFormControl">
<ng-generic-radio-option *ngFor="let val of optionVal" [value]="val">
<p *selectedState>selected {{val}}</p>
<p *unSelectedState>not selected {{val}}</p>
</ng-generic-radio-option>
</ng-generic-radio-group>

3.2 ts file

export class DemoComponent {
optionVal = [
'option-1',
'option-2',
'option-3',
]

constructor(){}
}

here is the stackblitz link for DEMO.

--

--

Vinit Tomar
Vinit Tomar

No responses yet