Resetting md-radio-button choices within an Angular 2 application

My Angular app has a sorting filter using radio buttons via md-radio-group for users to choose how they want data displayed. The radio buttons work fine, but I'm struggling to clear them when the "Restore Defaults" button is clicked.

This is the code for my view:

<filter-option name="Sort"
            placeholder="Select Sorting Option"
            [usePlaceholder]="!value"
            [visible]="sortFilters.enabled">
        <filter-label>{{value | capitalize}}</filter-label>
        <filter-menu>
            <md-radio-group class="mat-radio-label-content">
                <md-radio-button value="alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'alphabetical')">
                    Alphabetical
                </md-radio-button>
                <md-radio-button value="reverse alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'reverse alphabetical')">
                    Reverse Alphabetical
                </md-radio-button>
                <md-radio-button value="numeric ID" class="vert-radiobox-list" (click)="onSortClicked(value = 'numeric ID')">
                    Numeric ID
                </md-radio-button>
            </md-radio-group>
            <button md-button class="restore-button" (click)="clearSortingFilters()">Restore Defaults</button>
        </filter-menu>
    </filter-option>

In my component, I initialize the filter like this:

sortFilters =
{
    enabled: true,
    value: false
};

And here's the function attached to the "Restore Defaults" button:

clearSortingFilters()
{
    this.sendSort.emit(this.value = '');
}

The line

this.sendSort.emit(this.value = '')
clears the selected filter label, but I need help clearing the radio button selections in the md-radio-group too.

Answer №1

Make sure to update your code as shown below for it to function correctly:

html

<md-radio-group class="mat-radio-label-content" [(ngModel)]="selectedValue">
     <md-radio-button value="alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'alphabetical')">
           Alphabetical
     </md-radio-button>
     <md-radio-button value="reverse alphabetical" class="vert-radiobox-list" (click)="onSortClicked(value = 'reverse alphabetical')">
           Reverse Alphabetical
     </md-radio-button>
     <md-radio-button value="numeric ID" class="vert-radiobox-list" (click)="onSortClicked(value = 'numeric ID')">
           Numeric ID
     </md-radio-button>
</md-radio-group>    
<button md-button class="restore-button" (click)="clearSortingFilters()">Restore Defaults</button>

ts

selectedValue: string;

clearSortingFilters(){
    this.selectedValue = null; // or false or ''
  }

For a functional demo, check out the plunkr here

Answer №2

Adding NgModel to your input value is crucial in this scenario. Consider using [(ngModel)]="reverse order" to achieve the desired outcome. Additionally, updating your OnClick function to set "reverse order" to false would be beneficial.

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

A guide on verifying the username, password, and chosen role from a database through the use of javascript/ajax or alternative validation methods

If the user's name, password, or role is incorrect, I want to display an error message using validations like AJAX/JavaScript. index.php <html> <head> </head> <body> <style> body { wi ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Strange behavior noticed in the app.get() method of Node.js Express

Seeking clarification regarding the behavior of app.get() in Express. It appears that the function is not triggered when the path includes .html at the end. In the code snippet provided, the console logs "test" if attempting to access /random/example, bu ...

Adding a div with a canvas element is malfunctioning

I've been experimenting with using canvg to convert an SVG within a div into a canvas. So far, the conversion is working fine but when I try to copy the innerHTML of the div to another div, it's not functioning properly. The canvas is being gener ...

Angular 11 project facing issues with Bootstrap 5 tooltip functionality

Embracing the power of Bootstrap 5.0.2 in an Angular 11 project, I included the following code: index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compa ...

Exploring the Concept of Callbacks in JavaScript

What happens behind the scenes when a function is passed as a parameter in JavaScript and how does the engine recognize it as a callback? ...

Navigating Express HTTP Requests within Apollo Link Context in a NextJS Web Application

Currently, I am in the process of developing a NextJS application and facing a challenge with accessing a cookie to utilize it for setting a Http Header within a GraphQL Request. For this task, I am integrating apollo-link-context. Below is the snippet of ...

Switch to using addresses instead of latitude and longitude coordinates when utilizing the Google Maps API

I am looking to utilize Google Map Markers to indicate the locations where our services are offered. The code I have created using latitude and longitude is functioning properly, however, for my project I need to display city names instead of lat/long ...

Prevent scrolling after every time the mouse wheel is used

I have created a function that increments a class on a list item, here is the code snippet: var scrollable = $('ul li').length - 1, count = 0; $('body').bind('mousewheel', function(e) { if (e.originalEvent.wheelDelta / ...

What could be causing the data I'm trying to show in Angular to be present but not visible on the screen?

UPDATE: After a suggestion from @Mathias in the comments, it appears that the *ngIf statement causing the issue is as follows: (*ngIf="currentUsername == chat.senderUsername else elseBlock1") I'm puzzled as to why this isn't working, since bot ...

Tips for eliminating contenthash (hash) from the names of JavaScript and CSS files

Google's cached pages are only updated once or twice a day, which can result in broken sites on these cached versions. To prevent this issue, it is recommended to remove the contenthash from the middle of the filename for JavaScript files and eliminat ...

Arrange search results using $in array parameter in MongoDB

My challenge involves managing two collections: users and items. Within the user.profile.savedItems array, items are saved in the following format: {"itemId" : "yHud5CWpdPaEc6bdc", "added" : ISODate("2014-09-12T22:28:11.738Z")} My goal is to retrieve ...

Utilizing the power of JavaScript within HTML to remove elements upon being clicked

Seeking help again for the page I'm building where I keep encountering errors. As a beginner, I find myself puzzled and in need of assistance. My task is to utilize a for loop to iterate over the images and attach an event listener to each one so that ...

Pausing the audio playback with a click of the mouse

As a beginner in front end development, I recently designed a simple website incorporating the Lightbox kit. One functionality I am currently working on is starting an audio track when a user clicks on a thumbnail image. However, I am seeking guidance on h ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

Tips for retrieving data sent through Nextjs Api routing

Here is the API file I have created : import type { NextApiRequest, NextApiResponse } from 'next/types' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() export default async function handler(req: NextApi ...

Apply various filters to extract and refine information from the database

I have successfully retrieved data from the database. The structure of the data is as follows: serie --- title (string) --- category (array) To filter the data, I have implemented a search filter using a computed property. This is how it looks: f ...

Sending a message in the DELETE route using express.js

I'm having trouble displaying a message after deleting a user. I attempted to use req.session properties and then retrieve them in the GET route, but they seem to not be available. Can anyone suggest a solution for fixing this code? router.get("/", ...