Is there an issue with validation when using looped radio buttons with default values in data-driven forms?

Within my reactive form, I am iterating over some data and attempting to pre-set default values for radio buttons. While the default values are being successfully set, the validation is not functioning as expected.


    <fieldset *ngIf="question.radioButtonList.length > 0">
      <div class="choice-list">
        <div *ngFor="let item of question.radioButtonList" class="choice-list-item">
          <input type="radio" [name]="choice" formControlName="choice" [id]="item.id" [value]="item.id" [checked]="question.answer.selectedChoiceId === item.id"/>
          <label>{{item.title}}</label>
        </div>
      </div>
    </fieldset>

In the form definition, I have specified a required validator for the 'choice' form control.

 
'choice': new FormControl('', Validators.required)

Although the radio button appears correctly checked within the loop, the validator indicates that it is invalid until manually clicked by the user.

Answer №1

One reason for this behavior is that the initial value in your form control is set as an empty string, which is considered valid. The [checked] attribute in your template is therefore ignored. To address this, it is important to specify the initial value when creating the form control:

'choice': new FormControl(someInitialValueHere, Validators.required)

(By the way, the required validation may not be necessary in this case, since a radio button cannot be unchecked)

If you are unable to set the initial value during form creation, you can utilize the patchValue method:

this.myForm.patchValue({choice: someValue})

This approach allows you to set the desired default value. However, you will need to implement logic to determine the default value based on your [checked] criteria. It might involve iterating through options to identify the appropriate default value.

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

Issue encountered while retrieving data from a json server using Angular (HttpErrorResponse)

I've been working on creating a task app for practice, and my goal is to retrieve all the task data from a JSON server. However, I'm encountering an issue where the data doesn't display in the browser console as expected, and instead, an err ...

"Benefit from precise TypeScript error messages for maintaining a streamlined and organized architecture in your

As I dip my toes into the world of functional programming with typescript for a new project, I am encountering some challenges. In the provided code snippet, which follows a clean architecture model, TypeScript errors are popping up, but pinpointing their ...

Troubleshooting Node Server Startup Problems in AngularJS 2

I've been working on an Angular 2 sample app that was functioning perfectly until recently. However, when I attempt to run it now, a particular error pops up in the terminal: app/idea.ts(3,8): error TS2304: Cannot find name 'date'. The con ...

Something went wrong: You cannot use this command while the Angular CLI is running within a workspace

My angular project suddenly started showing the error message "Error: This command is not available when running the Angular CLI inside a workspace." Now, I can only use "ng serve" and not "ng n c". Any ideas on how to fix this? Angular Version: Angular C ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

I'm struggling to find the right Typescript syntax for defining a thunk function that returns a value while using React Redux Toolkit

Currently, I am utilizing TypeScript within a React Redux Toolkit project. While attempting to create an Async Thunk action function that is expected to return a boolean value, I found myself struggling with determining the correct TypeScript syntax: expor ...

What is the correct way to include an NPM package in a Plunker project?

Encountered an error while utilizing angular2-infinite-scroll. Attempting to replicate it in a plunkr. Experimented with using npmcdn, hence added this line in the index.html file: <script src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protectio ...

Strategies for persisting data in React using local storage to ensure information is retained after page refresh

I am attempting to store searched recipes data in local storage so that when the user refreshes, the data from the last searched recipe will still be available. I have tried saving the recipes data to local storage when a new search request is made and se ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

Customize the form using a custom component in react-hook-form: setting a default value

I have been learning ReactJS + TypeScript for 3 months now. Recently, I have a question about using react-hook-form (v7) to edit a form. I want to integrate my custom component into the form and I managed to do it on my own! Here is a snippet of my form p ...

The Material design paginator fails to function properly when used with dynamically generated tables

I have successfully implemented multiple tables with multiple columns using material table. However, I am encountering an issue when trying to paginate the results of each table. It appears that the pagination is not referencing each individual table, caus ...

Differentiate the array type within an object in TypeScript

I understand how to specify the type for a variable. let members: string[] = [] // this example works flawlessly My goal is to have an array of strings within an object. How can I structure it correctly? const team = { name: String, members<st ...

Guide on utilizing CanActivateFn in Angular 16 through constructor-based injection techniques

How do I utilize the latest CanActivateFn feature in Angular 16 with Dependency Injection? The new version of Angular 16 now uses a function instead of a class for the canActivate functionality. Below is my implementation. How can I incorporate my depende ...

Changing TypeScript Enum from String to Number in Angular

Does anyone know how to convert a Typescript enum value to a number for display in a dropdown but passing the numeric value on submit? Here is how the enum is currently set up: I am currently able to output the string key of the object when it is emitted ...

Tips for sending code confirmation in Amazon Cognito identity using nest.js

Having some issues with implementing AWS Cognito login in Nest.js? Check out this helpful guide on token validation: https://medium.com/weekly-webtips/token-validation-with-aws-cognito-and-nestjs-6f9e4088393c. I need to add a feature where users receive ...

When should I schedule the execution of the .spec and .po.ts files in Protractor?

Curious about TypeScript and Protractor: I have a couple of basic helper functions stored in a shared.po.ts file within my Protractor suite. These functions are triggered by the third it() in my .spec file - meaning they are not immediately called upon ru ...

Substitute the existing path with an alternative route

To move to a different route in Angular 2.0, we typically use route.navigate( [ 'routeName' ] ). However, this approach adds the current route to the browser's history. Is there a technique available to substitute the current route in the ...

Issue in Angular when using a shared module: displaying "appears in XXX.module but itself has errors" message

In my Ionic v6 project with Angular, I have developed multiple directives that are needed across various pages. To manage these directives effectively, I have created a shared module: import { MediaPage } from './../directivas/media/media.page'; ...

There is no ElementRef present in the HeaderComponent type

Task: Implement code to detect mouse clicks inside or outside a specified component, leading to an error message stating that 'elementref' does not exist within the 'Headercomponent' type. import { OnInit, Input, Output, ElementRef } f ...

Exploring the latest whatwg-fetch update with TypeScript version 2.5.3

Within my TypeScript project, I am currently utilizing "whatwg-fetch": "2.0.3" as the latest version of this polyfill. Additionally, for types, I am using version "@types/whatwg-fetch": "0.0.33", and everything functions smoothly when working with TypeScri ...