Utilizing Typescript in Angular to dynamically change mat-radio-button options

I am experiencing a successful operation with my mat-radio-button component.

However, my goal is to programmatically select the correct button once I receive the necessary parameters.

Below is the HTML code snippet:

      <form [formGroup]="seasonFrmGroup">
        <mat-radio-group aria-labelledby="radio-group-label2" class="radio-group" [(ngModel)]="selectedSeasonType"
          formControlName="btnSeason" fxLayoutAlign="center">
          <mat-radio-button class="radio-button" selectedSeasonTypevalue="s" (change)="radioChoiceSeason('s')">
            {{'Season' | translate }}
          </mat-radio-button>
          <mat-radio-button class="radio-button" selectedSeasonTypevalue="p" (change)="radioChoiceSeason('p')">
            {{'Playoffs' | translate }}
          </mat-radio-button>
        </mat-radio-group>
      </form>

In my .ts file, I aim to automatically select the radio-button with the 's' parameter:

ngOnInit() {
  this.seasonFrmGroup = new FormGroup({
    'btnSeason': new FormControl()
  });

  this.seasonFrmGroup.get("btnSeason").patchValue("s");
}

Unfortunately, I'm encountering the following errors:

ERROR Error: formGroup expects a FormGroup instance. Please pass one in. ERROR TypeError: Cannot read properties of undefined (reading 'get')

It has been a while since I last updated this code, and I am struggling to identify the missing piece to resolve these issues. Any guidance on how to correctly select my radio-button during initialization would be greatly appreciated. Thank you.

Answer №1

Avoid using ngModel in conjunction with reactive forms,

ngModel is no longer recommended

Instead, consider implementing an approach like the following,

Your component class can be structured as follows,

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
    title = 'stackoverflow-examples';
    seasonFrmGroup: FormGroup;

    constructor(
      private fb: FormBuilder
    ) { 
      this.seasonFrmGroup = new FormGroup({
        'btnSeason': new FormControl('')
      });
    }

    ngOnInit() {
      this.seasonFrmGroup.valueChanges.subscribe(
        val => {
          // Easily access and track changes in values
          console.log('Value of button clicked/selected',val.btnSeason);
        }
      );

      
      this.seasonFrmGroup.patchValue({
        btnSeason: 's'
      });
    }

    radioChoiceSeason(val: any) {
     //Implement your functionality here for when the button is clicked
    }
}

Your HTML template for the reactive form can be structured like this,

<form [formGroup]="seasonFrmGroup">
  <mat-radio-group aria-labelledby="radio-group-label2" class="radio-group"
    formControlName="btnSeason" fxLayoutAlign="center">
    <mat-radio-button class="radio-button" value="s">
      {{'Season' | translate}}
    </mat-radio-button>
    <mat-radio-button class="radio-button" value="p">
      {{'Playoffs' | translate}}
    </mat-radio-button>
  </mat-radio-group>
</form>

Refer to the screenshot below for visualization, https://i.sstatic.net/vu8o5.png

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

I encountered an issue with compiling my Docker file containing .NET Core and Angular 7 due to a problem with node sass. The Single Page Application (SPA)

Trying to launch a .NET Core app with Angular using spa middleware in a docker container has been quite the challenge. Initially, I encountered an issue when setting up a new angular app in Visual Studio 2017 Pro with docker support because NPM was missing ...

Angular nested routes allow for creating more complex and dynamic

I'm facing an issue with setting up nested routes in my myfile.routing.module.ts file. Whenever I try to access a specific route, it keeps redirecting me back to the home page. Below is the snippet of my code: routing.module.ts . . . const routes: R ...

Displaying a horizontal scroll bar for legends in ECharts can be achieved by limiting the legend to three lines. If the legend items exceed this limit, they will scroll horizontally to accommodate all items

I am currently utilizing ECharts to display trend data in a line chart format. With 50 different series to showcase, each series comes with its own legend. My objective is to arrange the legends at the top of the chart, while limiting them to a maximum of ...

RXJS expand keeps on recursing indefinitely

After successfully uploading a file to Firebase, I implemented a recursive function to listen for GCP trigger logs. Everything seems to be working well, but I'm facing an issue where the recursive expand function never exits. Despite checking the val ...

Combining the JSON code coverage reports generated by both Cypress and Karma does not yield an accurate outcome

In my angular project, I am testing it using the built-in unit testing tool (karma) and Cypress. My goal is to combine the code coverage reports from both tests. I have successfully set up the coverage configurations and merged the outputs using `nyc merg ...

Error: Encountering difficulty locating the necessary stylesheet for import during the construction of an Angular15 build, while also utilizing Kendo UI

Following the update to Angular 15, I encountered an error while using Kendo UI for the UI controls. It appears that the use of the tilde key is now deprecated. ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): S ...

Turning ngIf from false to true upon clicking the back button

I added an ngIf directive to hide a button on click and then move on to the second component. In the second component, I included a back button to return to the first component. However, when I click "back" to go to the first component, the ngIf remains fa ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

The PrimeNg confirmDialog is updating my navbar with some modifications

Despite my navbar working well and being fully responsive, I encountered an issue where opening a confirm dialog in the background caused the navbar width to expand to 800px even though the screen width was 1480px, creating empty space on the right side, a ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

Issue encountered while attempting to utilize the useRef function on a webpage

Is it possible to use the useRef() and componentDidMount() in combination to automatically focus on an input field when a page loads? Below is the code snippet for the page: import React, { Component, useState, useEffect } from "react"; import st ...

Error NG0304: The element 'mat-select' is not recognized in the template of the 'LoginPage' component

After creating a basic app, I decided to incorporate Angular Material into my project. The app in question is an Ionic 6 / Angular 14 app, however, I encountered an error while attempting to implement mat-select: https://i.sstatic.net/Quc53.png To addres ...

Discovering the Cookie in Angular 2 after it's Been Created

My setup includes two Components and one Service: Components: 1: LoginComponent 2: HeaderComponent (Shared) Service: 1: authentication.service Within the LoginComponent, I utilize the authentication.service for authentication. Upon successful authent ...

Utilizing ngFor in Angular to iterate through an array and retrieve the count of elements while displaying their

I utilized the following angular functions to display the data: availableLockers = [ { "lockerCode": "L01", "allocStatus": "alloc" }, { "lockerCode": "L02", &qu ...

Angular 7 swiper experiencing navigation issues

I have been attempting to implement the swiper slider but I am facing issues with navigating through slide content. You can find my code on stackblitz - swiper in the last horizontal tab. Here is the TypeScript code: ngOnInit() { var swiper = new Sw ...

Encountering an issue upon launching the application: "Error: Token is required in order to proceed!"

I encountered the following error. Can someone please point out what's causing it? How can I resolve this issue? Could there be something missing in main.ts? Error: (index):39 Error: Error: Token must be defined! at new BaseException (https:/ ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

Difficulties Arising in Flex Layout Usage Due to ngFor Loop Implementation

Despite my efforts, I couldn't locate a question quite similar to mine. If an answer already exists somewhere, I apologize. I'm trying to create a simple flex layout in row format where 2 containers are placed side by side. Inside another compon ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

The onShown event in ngx-bootstrap's datePicker is fired just before the calendar actually becomes visible

Recently, I've been exploring the capabilities of ngx-bootstrap's rangeDatePicker. My current challenge involves attempting to automatically navigate to the previous month as soon as the user opens the rangeDatePicker. To accomplish this, I have ...