Having trouble accessing previously submitted form values in Angular

When I try to update the form, I notice that my meetupform.controls.day array is not retaining the previously selected values

app.component.html

<div *ngIf="meetupForm.controls.recurring.value==='weekly'">
    <mat-checkbox (change)="onDayChange(day, $event.checked)" *ngFor="let day of days" class="margin-lr" [checked]="isClassDay(day)">{{day}}</mat-checkbox>
  </div>

app.component.ts

onDayChange(day: string, isChecked: boolean) {
const dayFormArray = <FormArray>this.meetupForm.controls.day;
if (isChecked) {
  // add to day array if checked
  dayFormArray.push(new FormControl(day));
} else {
  // remove from day array if unchecked
  const index = dayFormArray.controls.findIndex(x => x.value === day);
  dayFormArray.removeAt(index);
}

}

Answer №1

If you want to avoid creating a new array instance every time the checked value changes, consider making use of a property in your component:

private dayFormArray: FormArray;

ngOnInit(){
   this.dayFormArray = <FormArray>this.meetupForm.controls.day;
}

onDayChange(day: string, isChecked: boolean) {
   if (isChecked) {
     // add to day array if checked
     this.dayFormArray.push(new FormControl(day));
   } else {
     // remove from day array if unchecked
     const index = this.dayFormArray.controls.findIndex(x => x.value === day);
     this.dayFormArray.removeAt(index);
   }
}

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

Experiencing a useContext error when implementing MDX with NextJS 13

I am currently working on integrating mdx files into Next.js 13. After completing all necessary configurations in next.config and creating the file structure, I have the following path within the app folder: > docs > components > accordion > pa ...

Navigate to the identical component using Angular

There is a situation where a user visits /details;id=1. In the DetailsComponent, there is a table displaying similar objects with a button that redirects to /details;id=x, where x represents the id of the object. After clicking on the button, the URL para ...

Tomcat serving Maven web app is unable to locate Angular's /assets/ directory

My web application built with Maven has a particular structure that includes directories like 'dist', 'errors', and 'WEB-INF' within the 'webapp' directory. The 'dist' folder specifically contains all of t ...

Node is experiencing difficulty incorporating the AWS DynamoDB package into the project

Important Note: Although AWS SAM and DynamoDB are mentioned here, this question is primarily related to the AWS JavaScript SDK, or potentially just a Node/NPM query at its core. It should be answerable by anyone experienced in developing Node/JavaScript ap ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

Tips for using the arrow keys to navigate the cursor/caret within an input field

I am trying to create a function that allows the cursor/caret to move inside an input field character by character using the arrow keys (ArrowLeft, ArrowRight) on a keydown event. Current Approach: const handleKeyDown = (e: KeyboardEvent<HTMLInputEle ...

Exploring the integration of JSON data requests into a SQLite database using Angular2 and Ionic2

I am currently facing an issue with inserting JSON format data from a request into a SQLite database within my app. Even though the database and table are set up properly, I am having trouble getting the INSERT function to work correctly. Below is the sn ...

Exploring the method to implement unit testing for a nested if condition using Karma-Jasmine within an Angular environment

I have a function and my unit test coverage is currently at 75%, but I am aiming for 100% coverage. This is the function in question: calculateRatingSummary(): void { if (this.averageRating > 0) { this.avgRatings = Math.trunc(this.averageRat ...

Event-Propagation in Angular 5 with mat-expansion-panel within another component

In my project, I am facing a challenge where I need to create multiple mat-expansion-panels within one mat-expansion-panel. Everything works fine except for the issue that when I try to open a child-panel, it triggers the close-event of the parent-panel. ...

What seems to be the issue with my @typescript-eslint/member-ordering settings?

I am encountering an issue where my lint commands are failing right away with the error message shown below: Configuration for rule "@typescript-eslint/member-ordering" is throwing an error: The value ["signature","public-static-field","pro ...

What are the best practices for utilizing the Express router efficiently?

When building a TypeScript REST API, is there any difference between router.get(); router.post(); router.patch(); router.delete(); ---------------- app.use(); app.use(); app.set(); and router .get() .post() .patch() .delete(); ---------- ...

The input elements fail to register the passed-in value until they are clicked on

I am experiencing an issue with my form element that contains a few input fields. Two of these inputs are set to readOnly and have values passed in from a calendar element. Even though the input elements contain valid dates, they still display an error mes ...

Having trouble with NativeScript debugging in WebStorm - breakpoints not triggering?

I am currently using WebStorm 2017.2.5 with NativeScript 3.3.1. (Check out my package.json file here) After setting up a run/debug configuration, I placed breakpoints in the following locations: However, when running the app, it does not stop at these br ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

Ways to change a value into int8, int16, int32, uint8, uint16, or uint32

In TypeScript, the number variable is floating point by default. However, there are situations where it's necessary to restrict the variable to a specific size or type similar to other programming languages. For instance, types like int8, int16, int32 ...

ERROR: Unhandled promise rejection: Route cannot be found. URL Segment: 'details'

My current setup involves a router configuration in my Angular application. Below is the code snippet showcasing my router settings: import { Route, RouterModule } from '@angular/router'; import { ProjectDetailsComponent } from '../componen ...

Angular application experiencing issues with fixed headers not scrolling correctly

I've been working on implementing a fixed header for one of my pages in an Angular application, but I'm having some trouble getting it to work as expected. Currently, when the user expands the accordions on the page and scrolls down, the headers ...

Exploring the World of Angularjs 2

Currently, I am diving into learning angularjs 2. I found a helpful git repository that I am following closely, which can be found here. The repository contains some interesting codes in the index.html file. <script src="node_modules/core-js/client/shi ...

Transform an Angular 2 application to seamlessly incorporate an SDK

I have been working on an Angular 2 application and I am curious if it is feasible to transform this into an SDK that can be easily integrated into other applications by simply adding script tags in their headers. If this conversion is not achievable, co ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...