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

Inability to use autofocus feature in Angular 4

I am trying to set autofocus on an element inside an ngfor loop. Below is the code from my chat.component.html file: <div *ngFor="let chat of chats; let last = last"> {{ chat.chat }} <span *ngIf="last;" autofocus></span> </div> ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Can someone guide me on finding my staticwebapp.config.json within Azure Devops for deploying Azure Static Web Apps during a release?

After setting up a pipeline to build the artifact for my Angular application, I encountered an issue with deployment where specific URLs would redirect me to a 404 error page. This problem seems to be related to the configuration in staticwebapp.config.jso ...

Accessing the element reference within a custom attribute directive in Angular through a projected template using ngTemplateOutlet

I'm encountering an issue when trying to adjust the css and click event on a custom attribute directive The DIV causing the problem is nested within a reference that is projected and passed into a child component. Here is the process: Add the ng-te ...

Use TypeScript to cast the retrieved object from the local storage

const [savedHistory, setSavedHistory] = useState(localStorage.getItem('history') || {}); I'm facing an issue in TypeScript where it doesn't recognize the type of 'history' once I fetch it from localStorage. How can I reassign ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

Successful build of node app, however, not appearing on Heroku for MEAN Stack application

After numerous failed attempts, I finally managed to successfully build and deploy my app on Heroku. However, when I tried to access it, all I got was an 'Application error'. The log for the successful build is as follows: -----> Node.js app d ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

I’m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...

The timezone plugin in day.js may sometimes generate an incorrect date

For a while, I've been using dayjs in my angular project to convert timestamps from UTC to localtime. However, after my recent update, this functionality stopped working. This isn't the first issue I've encountered with dayjs, so I decided t ...

Exploring the Differences Between ionViewWillEnter and ionViewDidEnter

When considering whether to reinitiate a cached task, the choice between ionDidLoad is clear. However, when we need to perform a task every time a view is entered, deciding between ionViewWillEnter and ionViewDidEnter can be challenging. No specific guid ...

Building a search feature with a customized pipe in Angular

I attempted to create my own custom pipe in Angular 6 for filtering a list of campaigns using a search box. Strangely, I am having trouble getting the filter to work on the campaign list. Below is the code snippet that I have written. This is the implemen ...

Utilizing TypeScript to mandate properties in a React component

When trying to apply TypeScript type enforcement on React components, I encountered some unexpected behavior. Here are simplified examples: function FunctionalComponent(props: { color: string }) { return <></>; } type ComponentWithName<I ...

Maintaining ongoing subscriptions using rxjs in Angular 5

As a newcomer to rxjs in Angular 5, I find it a bit challenging to articulate my question, but I am hopeful for some guidance. I frequently encounter the same setup: Multiple Components to display identical data A single Service for accessing the data ...

Removing multiple httpparams in Angular: A step-by-step guide

When working with APIs, there are times when custom parameters are added for specific use cases that do not need to be sent to the backend. In such situations, it is necessary to delete these parameters before sending the request to the backend. Url: https ...

Is it possible to include parameters in an HTML GET request with Electron.Net?

I have successfully implemented a function in an Angular component within an Electron application using HttpClient: var auth = "Bearer" + "abdedede"; let header = new HttpHeaders({ "Content-Type": 'application/json&a ...

No types are assigned to any props

I recently began working on a SvelteKit skeleton project for my personal website. However, I encountered an error when using Svelte with TypeScript - specifically, I kept getting the message Type '<some prop type>' is not assignable to type ...

Removing invalid characters in a *ngFor loop eliminates any elements that do not meet the criteria

I am facing an issue with my *ngFor loop that is supposed to display a list of titles. fetchData = [{"title":"woman%20.gif"},{"title":"aman",},{"title":"jessica",},{"title":"rosh&quo ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...