Activate the event when the radio button is changed

Is there a way to change the selected radio button in a radio group that is generated using a for loop? I am attempting to utilize the changeRadio function to select and trigger the change of the radio button based on a specific value.

<mat-radio-group (change)="onHobbyChange()">
      <mat-radio-button *ngFor="let hobby of hobbies" [value]="hobby.favorite">
      </mat-radio-button>
</mat-radio-group>

changeRadio(value){
    const event = new MouseEvent('click', {bubbles: true});
    this.matRadioButton._inputElement.nativeElement.dispatchEvent(event);
}

I attempted to use _inputElement but it appears to always select the first element and does not trigger the change event as desired.

Answer №1

If you prefer not to utilize ngModel or formControl, you have the option of using component variables

Check out this example: View full code here

export class RadioNgModelExample {
  favoriteSeason: string;
  seasons: string[] = ['Winter', 'Spring', 'Summer', 'Autumn'];

  whenSeasonChange() {
    this.favoriteSeason = 'Summer';
  }

  onSeasonChange(event: any) {
    this.favoriteSeason = event.value;
  }
}

<label id="example-radio-group-label">Choose your favorite season</label>
<mat-radio-group
  aria-labelledby="example-radio-group-label"
  class="example-radio-group"
  (change)="onSeasonChange($event)"
>
  <mat-radio-button
    class="example-radio-button"
    *ngFor="let season of seasons"
    [value]="season"
    [checked]="season === favoriteSeason"
  >
    {{season}}
  </mat-radio-button>
</mat-radio-group>
<div>Your favorite season is: {{favoriteSeason}}</div>

<button (click)="whenSeasonChange()">Click to select Summer</button>

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

The component's state consistently reverts to its initial state

I am working with a component called DataGrid that has the following state: const [rows, setRows] = useState([ { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'}, { id: 2, lastName: 'Lanniste ...

When utilizing two-way binding in reactive forms, the mat-select component may fail to show the selected value

Here is the code for a Reactive Form: createInputForm() { console.log('creating form'); this.instituteForm = this.formBuilder.group( { address: [this.instituteData.address, Validators.required], city: [this.institu ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Use jQuery to switch back and forth between the login and registration forms on a single

I've set up two forms, one for login and one for registration, with the default view showing the login form. There's a link that says "Don't have an account?" and when it's clicked, the registration form will display while the login for ...

AngularJS Cascading Dropdowns for Enhanced User Experience

There is a merchant with multiple branches. When I select a merchant, I want another dropdown list to display the data from merchant.branches. The following code does not seem to be fixing the issue: <label>Merchant:</label> <select ng-if= ...

Typescript libraries built specifically for unique custom classes

I am currently exploring the most effective method for creating a class library in Typescript and deploying it to NPM along with a definitions file. The classes within the library serve as models that are utilized by multiple RESTful services. Some of the ...

Is it deemed as an anti-pattern to establish directives for styling?

Currently, I am in the midst of developing a specialized component UI library for a specific project I'm involved in. This library will consist of unique stylized components with elements that are reused throughout. As I work on this project, I find ...

"Upon refreshing, the background image reverts back to its original default setting

With React, I have implemented a feature where users can navigate to their 'settings' page and select an image to set as their background. I used DOM manipulation to achieve this functionality successfully! However, whenever the page is refreshed ...

Avoiding page refresh while submitting a form can be tricky, as both e.preventDefault() and using a hidden iFrame seem

I've been stuck on this issue for a while now, scouring Stack Overflow and Google for solutions, but nothing seems to be working. My main goal is to avoid page reloads after uploading a file because it resets the dynamic HTML I need to display afterwa ...

Is there a way to upload numerous images from my local disk onto a canvas using Fabric.js?

I'm currently working on an innovative Image Collage application using the power of HTML5 canvas and Fabric.js. One of the key features I want to implement is the ability for users to simply drag and drop files into the designated 'File Drag and ...

Adjusting the color of specific sections within a text box

Can I change the color of a specific section of a text input box? I'm working on a comment widget that needs everything between the @ and : symbols to be in a different color: <input type="text" placeholder="Want To Say Something?" value="@user55 ...

tips for transferring API JSON response parameters to material ui table

I'm currently working on creating a table with the material UI. My goal is to populate the rows of the table based on the data received from an API response. The challenge I'm facing is that the API response includes an array of objects with mult ...

What is the best way to receive a notification when a user chooses any option in a Material UI Autocomplete React component?

My dilemma involves using an autocomplete feature that doesn't behave as expected. I am looking to detect when an option is selected, regardless of whether it's the same as the last selection. The onChange event I'm using only triggers if th ...

Passing a boolean value from the parent Stepper component to a child step in Angular

I am facing an issue with passing the boolean value isNewProposal from a parent Angular Material stepper component to its children steps. Despite using @Input(), the boolean remains undefined in the child component, even after being assigned a value (true ...

Creating flexible layouts in Angular 2+ by dynamically adjusting element width based on available space

When working with Angular 2+, I always take into consideration the proper setting of element widths. My initial approach involves assessing the available space within the parent element and then adjusting the width of child elements to evenly fill this all ...

Next.js Server Error: ReferenceError - 'window' is undefined in the application

I am currently in the process of integrating CleverTap into my Next.js application. I have followed the guidelines provided in the documentation Web SDK Quick Start Guide, however, I encountered the following issue: Server Error ReferenceError: window is ...

What is the best way to manage a 301 redirect from a current page to a new page within my index.js script?

Hello everyone, hope you're having a great Friday! I'm looking for advice on the best approach to handle a 301 redirect in node.js from an existing file to another file. Let's say I currently have a file called /contact router.get('/con ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

Issue: Package 'cairo' not located on EC2 Bitnami MEAN server

Setting up my MEAN application on a Bitnami server has been quite a challenge. During the installation of dependencies, I encountered an error that I just can't seem to resolve. Despite following the instructions provided in the error message, I am st ...

Discovering the bottom scroll position in an Angular application

I am working on implementing two buttons on an Angular web page that allow the user to quickly scroll to the top and bottom of the page. However, I want to address a scenario where if the user is already at the very top of the page, the "move up" button sh ...