What is the best way to set default values for an array in Angular when the data is loaded dynamically?

I have an Array named 'habits' that looks like this: https://i.sstatic.net/x3aYz.png

I am displaying it in a table with radio buttons for yes and no options.

https://i.sstatic.net/iAsqO.png

 <tr *ngFor="let habits of masterDate.data.habits; index as x">
    <th class="tbl-border-right-bottom text-wrap" style="width: 50%">
        {{ habits.name }}
        <div hidden="true">
            <input type="text" formControlName="habitsSufferedMainId{{ x }}" />
        </div>
    </th>
    <td class="tbl-border-right-bottom">
        <div class="col-md-6">
            <div class="form-group d-flex justify-content-around pr-2">
                <div class="custom-control custom-radio">
                    <input type="radio" class="custom-control-input" id="habitsSufferedMain{{ x }}" value="1" name="habitsSufferedMain{{ x }}" formControlName="habitsSufferedMain{{ x }}" />
                    <label class="custom-control-label" for="habitsSufferedMain{{ x }}">Yes</label>
                </div>
                <div class="custom-control custom-radio">
                    <input type="radio" class="custom-control-input" id="isMainHabitNo{{ x }}" value="0" name="habitsSufferedMain{{ x }}" formControlName="habitsSufferedMain{{ x }}" [checked]="true" />
                    <label class="custom-control-label" for="isMainHabitNo{{ x }}">No</label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <textarea placeholder="If 'Yes', please provide details" class="form-control form-control-sm" rows="2" formControlName="habitsSufferedMainReason{{ x }}"></textarea>
        </div>
    </td>
 </tr>
  1. Does anyone know how to set the default value to "No"?

Answer №1

Start by creating a map to hold the outcomes

const results = new Map<number, boolean>();

To initialize the checkbox value, use FormControl()

 const habitOne = new FormControl(false);
 results['habitOne'].set(false);

Next, observe changes in the value and store them in the map

habitOne.valueChanges.subscribe(value => {
    results.set('habitOne', value)
})

If you prefer, utilize a loop with FormBuilder (ensure all inputs are within a reactive form <form [formGroup]=form>)

form: FormGroup;

constructor(private fb: FormBuilder) {
    this.form = this.fb.group(
      this.habits.reduce((controls, habit, index) => {
        this.results.set(index, false)
        return {
        ...controls,
        [`habit${index}`]: new FormControl(false)
      }
    }, {}));

    Object.keys(this.form.controls).forEach((control, index) => {
        control.valueChanges.subscribe(value => {
            this.results.set(index, value == true)
        })
    }
  }

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

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

Is there a way to prompt the browser's default handler to execute prior to the event propagation?

When working with a textbox (<input type="text">) in the browser, it's important to note that keystrokes are not processed until after all JS event handlers have completed execution. In my application, I encountered a scenario where a ...

Resolving undefined in Ionic 4: Returning Data from Modal

I'm attempting to create a modal window that utilizes a radio group. When a user selects a value from the radio group, I want the modal to return the selected object. Here is the code for the radio group page and HTML: export class PopoverstationsPa ...

Tips for downloading a file using an AWS Lambda function in Python

I'm currently exploring ways to receive a file sent by a web browser through an API call in Python. The web client has the capability to send various file types (such as .txt, .docx, .xlsx, etc.). I am uncertain whether I should handle them as binary ...

What steps can be taken to ensure that the requestAnimationFrame function does not redraw the canvas multiple times after a button click?

I am currently working on a project where I am drawing a sin wave on a canvas and adding movement to it. export class CanvasComponent implements OnInit { @ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>; ...

retrieving information from an array of objects within a nested JSON array

Struggling to extract information from an API set. When viewed in Postman / Insomnia, the body looks like this: { "responses": { "log": [ { "id": 123, "date": "2022-01-01T01:12:12.000Z", ...

Exploring Angular: How to access ViewChild from a dynamically loaded component

One of my components includes a ViewChild element like this: @ViewChild('overView') content: ElementRef; I am dynamically loading this component in the following way: let overviewComponent = this.vcr.createComponent(OverviewComponent); let conte ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

When working with Laravel and submitting a form using the `multipart/form-data` encoding type, you may encounter the

When sending a request that includes form data object with some data from angular 4 to laravel api, sometimes the request data is received correctly and other times it is null, referred to as 'empty request.' Below are the details of my request: ...

Reactive form utilizing Angular template

While working on our application, I observed a significant amount of duplicate code present in the HTML structure of our forms. Most input elements follow the same pattern, prompting me to consider creating a generic input component to streamline and tidy ...

I encountered an issue while trying to view an image using ionic-img-viewer - the error that came up was "Module not found: rxjs/operators

I encountered an issue when attempting to use the Programmatic ionic-img-viewer which resulted in an error: Uncaught Error: Cannot find module "rxjs/operators". Below are the relevant code snippets: import { IonicImageViewerModule } from 'ionic-img- ...

The 'subscribe' property is not recognized on the 'void' type

Hey there, I'm currently working on an Angular web API project and running into an error with the subscribe keyword. I've already imported observable but the error persists. If anyone has come across this issue before, I would greatly appreciate ...

Creating an image tag in Angular4 using data retrieved from an API_RESPONSE

Currently, I am developing a web application using Angular4. One of the requirements is to display images based on the response from an API. When a user clicks on a product in the application, the product name is sent to the API which responds with relate ...

When a reusable component that utilizes ControlValueAccessor is modified programmatically, it triggers the onChange event

Currently, I am working on a mobile application using Ionic and Angular, incorporating Reactive Forms. One of the challenges I am facing involves a reusable component for entering phone numbers. This component utilizes the ControlValueAccessor interface. ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

Puppeteer occasionally fails to execute clicks

I am experiencing a problem with the click behavior that I just can't seem to resolve. Configuration Typescript: 2.9.0-insiders-20180510 Jest: 22.4.3 Puppeteer version: 1.4.0 Platform / OS version: Win10 Node.js version: 8.9.0 Code Snippet await ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

Looping through an array using NgFor within an object

I've been working on pulling data from an API and displaying it on a webpage. Here is the JSON structure: {page: 1, results: Array(20), total_pages: 832, total_results: 16629} page: 1 results: Array(20) 0: adult: false backdrop_path: "/xDMIl84 ...

Encountering "Undefined error" while using @ViewChildren in Angular Typescript

In my application, I am facing an issue with a mat-table that displays data related to Groups. The table fetches more than 50 rows of group information from a data source, but initially only loads the first 14 rows until the user starts scrolling down. Alo ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...