How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" until another anchor is selected, providing the user with visual feedback.

Here is a Plunker example

I'm new to Angular2 and Typescript, so I'm unsure if there's a built-in feature in Angular that can handle this functionality. In jQuery/JS, I would add a class to each anchor for easy selection, remove the clicked class from all anchors when a new one is clicked, and then add the clicked class to the newly selected anchor. Angular's [routerLink] can take care of the routing part.

The current markup is designed with a jQuery solution in mind because I haven't found a way to remove a CSS class directly in Typescript. While I could control styles through interpolation like [style.color], it would require storing style values for each anchor individually. There must be a simpler approach!

<md-sidenav #start mode="over" class="sideDrawer">
  <ul>
    <li><a href="#" class="anchor" id="a11" (click)="sideNavAlert($event)">anchor 1.1</a></li>
    <li><a href="#" class="anchor" id="a12" (click)="sideNavAlert($event)">anchor 1.2</a></li>
    <li><a href="#" class="anchor" id="a13" (click)="sideNavAlert($event)">anchor 1.3</a></li>
  </ul>
  <ul>
    <li><a href="#" class="anchor" id="a21" (click)="sideNavAlert($event)">anchor 2.1</a></li>
    <li><a href="#" class="anchor" id="a22" (click)="sideNavAlert($event)">anchor 2.2</a></li>
    <li><a href="#" class="anchor" id="a23" (click)="sideNavAlert($event)">anchor 2.3</a></li>
  </ul>
  <ul>
    <li><a href="#" class="anchor" id="a31" (click)="sideNavAlert($event)">anchor 3.1</a></li>
    <li><a href="#" class="anchor" id="a32" (click)="sideNavAlert($event)">anchor 3.2</a></li>
    <li><a href="#" class="anchor" id="a33" (click)="sideNavAlert($event)">anchor 3.3</a></li>
  </ul>
</md-sidenav>

Answer №1

Achieving this with Angular 2 is a smooth process. Simply utilize the [ngClass] binding as shown below:

To implement this in your app.component.html, make the following updates:

 <md-sidenav #start mode="over" class="sideDrawer">
      <ul>
        <li><a href="#" [ngClass]="setClasses('a11')" id="a11" (click)="sideNavAlert($event)">anchor 1.1</a></li>
        <li><a href="#" [ngClass]="setClasses('a12')" id="a12" (click)="sideNavAlert($event)">anchor 1.2</a></li>
        <li><a href="#" [ngClass]="setClasses('a13')" id="a13" (click)="sideNavAlert($event)">anchor 1.3</a></li>
      </ul>
      <ul>
        <li><a href="#" [ngClass]="setClasses('a21')" id="a21" (click)="sideNavAlert($event)">anchor 2.1</a></li>
        <li><a href="#" [ngClass]="setClasses('a22')" id="a22" (click)="sideNavAlert($event)">anchor 2.2</a></li>
        <li><a href="#" [ngClass]="setClasses('a23')" id="a23" (click)="sideNavAlert($event)">anchor 2.3</a></li>
      </ul>
      <ul>
        <li><a href="#" [ngClass]="setClasses('a31')" id="a31" (click)="sideNavAlert($event)">anchor 3.1</a></li>
        <li><a href="#" [ngClass]="setClasses('a32')" id="a32" (click)="sideNavAlert($event)">anchor 3.2</a></li>
        <li><a href="#" [ngClass]="setClasses('a33')" id="a33" (click)="sideNavAlert($event)">anchor 3.3</a></li>
      </ul>
    </md-sidenav>

Subsequently, in the app.component.ts, add the following:

export class AppComponent {

    private selectedAnchorId: string;
    sideNavAlert(e): void {
      this.selectedAnchorId = e.currentTarget.id;
    }

    setClasses(elementId){
      return {
        anchor: true,
        anchorClicked: this.selectedAnchorId === elementId
      };
    }
}

Answer №2

If you are working with Angular 2, one way to add classes to your element is by using the syntax

[class.myclass]="boolean expression"
. When the boolean expression evaluates to true, the class myclass will be applied to the element. You can use any valid javascript expression, including method calls, as the condition.

Another option is to apply multiple classes at once using the syntax:

[class]="myclass1 myclass2 myclass3"
. In this case, you provide a string that includes all the class names you want to add to the element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

"Improvements required for the search and filter functionality in the JSON

My JSON function retrieves image data and displays it in panels. Here is an example of the code: $.getJSON('iproducts.json',function(products){ var output = ""; $.each(products.appleitems, function(i, product) { output += "<di ...

Setting the initial selected option in a dropdown using Angular 4 Reactive Forms

One of the challenges I faced in Angular 4 was displaying a dropdown list with countries using a Reactive module. To achieve this, I had set up a configuration in a json file as follows: countries: ['USA', 'UK', 'Canada']; ...

The combination of React, Typescript, and MaterialUI Paper results in a stunning design with a sleek and

Whenever I include <Paper elevation={0} /> within my react component, I encounter the following issue: Cannot read properties of undefined (reading 'background') TypeError: Cannot read properties of undefined (reading 'background&apos ...

Tips for adding event listeners to dynamically-loaded content using AJAX

I need help with the following code snippet: $("#contantainer").load("some_page.txt"); Inside some_page.txt, I have the following content: <div class="nav"> <ul id="nav_ul"> <li><a class="nav_a" href="#home" id="home"> ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

Store Form Input as JSON Data File

Seeking advice on the optimal method to save submitted form data to a separate file called data.json, for future reference. The form layout is quite basic: <form> <fieldset> <label for="name">Name:</label> &l ...

Activate anchor classes in several anchor link menus simultaneously

I have a one-page website with multiple menus filled with anchor links. Here is an example of what they look like: <ul> <li><a href="#home" class="active" onclick="closeNav();">Home</a></li> <li><a href="#abo ...

Having trouble retrieving the selected dropdown value in Angular 5 using <p-dropdown> from PrimeNG due to issues with the ngOnInit function. Need some assistance with

My values are currently being populated in the ngOnInit() method, so the event is not available there. I need to retrieve the previously selected value even after refreshing the page. <p-dropdown [options]="Options" [(ngModel)]="Id" (onChange)="onChang ...

What measures can be taken to deter users from navigating to a different webpage?

This HTML code includes an image that is linked to another page. <a href="#" class="dead_prfile_step_next ADInNext"> <img alt="next" src="/Content/DesignFiles/@Html.R(VirtualPath, "dead_profile_free_buttons_next.png")" /> </a> Here is ...

Utilizing Angular's reactive forms to populate an array field with an array of data

I am currently using Angular 6 along with Reactive form to create a form. Within the ngOnInit() function, I have set up a form group in the following manner: this.landingPageForm = this.formBuilder.group({ title: new FormControl('', [ Val ...

Merge two distinct arrays of objects based on a shared field

I have two arrays of objects that I need to merge, with the expected output as: [ { "scenario": [ { "errorname": "Error 01", "status": 5, "desc_1" : "test", "desc_2" : "testing" }, ...

Blob is unable to open the PDF file as it is not

Currently, I am utilizing ASP.NET Core and Angular to create a web application. In one of the controller actions, I am returning a File like this: return Ok(Microsoft.AspNetCore.Mvc.File(await GetFileContents(args), "application/pdf")); Then in TypeScript ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Storing information from a signup form using Angular

Can you help with my registration form? <div class="form-group"> <label for="email" class="col-sm-3 control-label">Email Address</label> <div class="col-sm-9"> <input type="email" id="email" placeholder="Enter your ...

Maintain the visibility of the Jquery modal regardless of page loading

Hello, I am just getting started with jQuery and have encountered an issue. When I try to display a jQuery modal on the click of an Upload button, it disappears immediately because of the page load. I would like the modal to stay visible until a button wit ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

Mistakes that occur while trying to expand a base class to implement CRUD functionality

Creating a base class in TypeScript for a node.js application to be extended by all entities/objects for CRUD operations is my current challenge. The base class implementation looks like this: export class Base { Model: any; constructor(modelName ...