Is it possible to modify the chosen radio button within a template-driven form by utilizing the change event of the radio button group?

Within my Angular Material application, I have implemented a radiobutton group containing two options: "Accept" and "Reject", with corresponding values as "A" and "R". When a user selects the "Reject" option, a confirmation dialog is displayed. If the user clicks "Cancel" in the confirmation dialog, I need to programmatically change the selected radio button back to "Accept".

The logic for handling this behavior is contained within the change event of the radiobuttongroup.

The radiobutton group is tied to a variable named "statusCode" using [(ngModel)], and is integrated into a template-driven form.

onRadioChange($event: MatRadioChange) {
    if ($event.value === 'R' && this.userNeedsToChange) {
       let result = confirm('Are you sure you want to reject? You cannot reverse this decision');
       if (!result) {
           this.statusCode = 'A';
       }
    }
}

Answer №1

To achieve your goal, there are generally two approaches: using either Reactive Forms or Template-driven Forms, as you mentioned.

If you want to change the value in a template-driven form, you need to utilize the LocalReference and @ViewChild() decorator in your component. Here's an example:

In HTML:

<mat-radio-group>
  <mat-radio-button value="1" #email>Email</mat-radio-button>  
  <mat-radio-button value="2">Mobile</mat-radio-button>    
</mat-radio-group>
<br/>

You can then use the local reference like "#email" in the component code, for instance:

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-reactive',
  templateUrl: './reactive-form.component.html'
})
export class TemplateFormComponent implements OnInit {
  constructor() {} 

  @ViewChild('email') 
  emailRB: MatRadioButton;


  RadioChanged( event ) {
    let result = confirm('Are you sure you want to reject? You cannot reverse this decision');
    if (!result) {
           this.emailRB.focus();
     }
  }

This code snippet can assist in selecting the desired radio button.

For more examples, refer to the link below:

However, the preferable method is utilizing Reactive Forms, such as:

<form class="radio-btn-container" [formGroup]="acceptanceFG">
  <label class="radio-main-lable">Acceptance: </label>
  <mat-radio-group formControlName="acceptance">
    <mat-radio-button value="A">
       <span class="radio-option-lable">Accept</span>
    </mat-radio-button>
    <mat-radio-button value="R">
       <span class="radio-option-lable">Reject</span>
    </mat-radio-button>
  </mat-radio-group>
</form>

And in the component file:

import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-reactive',
  templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent implements OnInit {

acceptanceFG: FormGroup;

constructor(private _formBuilder: FormBuilder ){}

  ngOnInit() {
    this.acceptanceFG= this._formBuilder.group({
       acceptance: new FormControl( null, { validators: Validators.required   }),
    });
  }

    RadioChanged( event ) {
    let result = confirm('Are you sure you want to reject? You cannot reverse this decision');
    if (!result) {
       this.acceptanceFG.patchValue( { acceptance: 'R' } );
     }
  }
}

I hope this explanation was sufficient and beneficial! 😉

Answer №2

HTML
    <mat-radio-button
    #myradio
    (change)="select(element)">
    </mat-radio-button>

TS
@ViewChild('myradio')
  myradio: MatRadioButton;


this.myradio.checked = false; //set to unchecked state

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

Retrieve a singular item using an HTTP GET request in Angular utilizing RxJS

I am currently working on implementing a feature on my website where users can enter an object's id and see the details of that specific object displayed. I have managed to fetch and display Observables for utilizing in *ngFor loop, but even a single ...

How can one properly conduct a health check on a Twilio connection using TypeScript?

How can I create an endpoint in TypeScript to verify if the Twilio connection is properly established? What would be the proper method to perform this check? Below is a snippet of my current code: private twilioClient: Twilio; ... async checkTwilio() { ...

TypeORM: Create case-insensitive search functionality

Creating a basic search feature where the records are as follows: AB CD A BCD ABC D ABD C If the search term is "BCD", the expected output should be: AB CD A BCD ABC D The current query looks like this: await connection.manager .createQueryBuilder(RefTra ...

Resolving naming conflicts in Angular templates: what's the solution?

Within my application, I have created two essential components: JokesList Joke The JokesListComponent is structured as follows: template: <app-joke *ngFor="let joke of jokes" [joke]="joke"></app-joke> @Component({ sel ...

The IntrinsicAttributes type does not contain a property called 'theme'

As a junior TypeScript developer, I am exploring the creation of a dark mode feature using styled-components and a custom hook in TypeScript. useDarkMode.tsx import { useState } from 'react'; export const useDarkMode = () => { const [theme ...

Encountering "Duplicate identifier" issues when using Angular2 and TSD

I am currently in the process of migrating a project from Angular 1 to Angular 2. The project involves client and server code, with some shared components. My goal is to implement Angular 2 on the client side by following the guidelines outlined in the ng2 ...

Utilizing MathJax in the AstroJS project to convert all [tex] code on the page into MathML code when building

In my latest project, I've implemented AstroJS as a Static Site Generator. One of the key benefits of utilizing AstroJS is its capacity to execute JS code within the --- --- code fences section of a .astro file, enabling the creation of webpages witho ...

Unable to access the 'filter' property of an undefined Array in Angular

Currently, I have an array named customerList: Array<String> = []; that is populated with values from a server-side function. Everything seems to be working well until I attempt to use the .filter() method on this array and encounter an error stating ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

Xcode 12.4 error: 'Notifications cannot be enabled' in Ionic 5

Since the Xcode 12.4 update, the Firebase Push Notifications have ceased functioning properly, displaying the error message "Notifications are not allowed for this application". I have made sure to update all Ionic, Angular, and Capacitor packages to the ...

Having trouble with an Angular subscribe error that says "Property 'subscribe' does not exist on type 'AngularFireList<unknown>'.ts(2339)"? Let's find a solution together!

My goal is to retrieve data from a Firebase RDB in the data service by using the following function: this.getOrgId() .subscribe((orgId: string) => localStorage.setItem('orgId', orgId)); getOrgId() { return this.db.list(/users/${this.uId ...

What is the best way to retrieve data in my client component without risking exposing my API key to unauthorized users?

To retrieve information, I plan to use pagination in order to specify a particular page number within the API URL and fetch additional data by updating the value of page. The process of fetching data in my server component is as follows: // fetchData.tsx ...

Ways to create a rotating effect using CSS and Angular

I'm working with Angular and I have a question: How can I make this icon rotate when I click on it? <div class="col-lg-1 col-md-4 col-sm-2 col-2 alend-text"> <i class="pomrgto iconfa fas fa-chevron-circle-right view_cir ...

"What is the best way to transform a POST curl request into an Angular HTTP POST request using gsutil for Google Cloud Storage

Currently utilizing GCP and GCS. I am attempting to send a POST request, however in the curl command below, I am unable to locate where to input the necessary data that needs to be sent. In this scenario, how can I implement a POST request using angular ...

Ramda in Typescript has unexpectedly encountered an error

While building my project (reactjs starter + typescript) on production, I encountered this TypeScript error: TypeScript error: Argument of type '<T>(list: readonly Record<"dataField", T>[]) => T[]' is not assignable to parameter.. ...

Guide on implementing conditional return types in React Query

In my approach, I have a method that dynamically uses either useQuery or useMutation based on the HTTP method passed as a prop. However, the return type of this method contains 'QueryObserverRefetchErrorResult<any, Error>', which lacks meth ...

How to authenticate users using JWT in Angular and retrieve user data?

I've developed an Angular project with JWT login functionality to communicate with the backend. Once I receive a token, my goal is to retrieve user information from the backend. Below is the code snippet from my authentication service: login(username: ...

Generate an auto-focus Power BI report seamlessly and effortlessly

I'm working on a straightforward Microsoft Power BI example that showcases a list of employees grouped by gender. <iframe width="300" height="200" src="https://app.powerbi.com/view?r=******" ></iframe> The issue I am facing is that the ...

When retrieving API data, the page refreshes automatically

Currently experimenting with the Github user API to understand how things function before incorporating it into a project. However, I've encountered an issue. const btn = document.querySelector('button') as HTMLButtonElement const input = do ...

The properties and methods of TypeScript classes that are exported do not exist (error code TS 2339)

I have a module containing various helper classes, each defined in their own files such as controller.ts and stateService.ts. To export all of them, I understand that creating an index.ts file that imports and exports them all serves as the interface to th ...