The value is not being found in my form, and the slide-toggle is consistently checked

I am encountering an issue with my forms. On the web, all my slide-toggle options are pre-checked as shown in the image provided.

I suspect that the problem lies within the patchFor(){} function. Could someone please review my code for me? I have attempted the following code:

ts:

homeboxsp: Package[] = [];   
activeHomeboxPForm: FormGroup;

this.activeHomeboxPForm = this.fb.group({
  'active': new FormControl('', Validators.required),
  'homeboxpackage_id': new FormControl('', Validators.required)

}); 

populateFormHomeboxP() {
    this.hsP.homeboxPGetAll().subscribe(
        homeboxsp => {
            this.homeboxsp = homeboxsp;
            this.patchForm();
        }
    )
}
patchForm() {
    this.activeHomeboxPForm.patchValue({
        active: this.homeboxsp.map(x => x.active),
        homeboxpackage_id: this.homeboxsp.map(x => x.homeboxpackage_id)
    });
    console.log(this.homeboxsp.map(x => x.active))
    console.log(this.homeboxsp.map(x => x.homeboxpackage_id))
}

The console displays my values. See the imageformconsole.

Here is the HTML:

<form [formGroup]="activeHomeboxPForm" class="col s12" materialize>
    <section class="example-section">
        <mat-slide-toggle formControlName="active" value="active"
        class="example-margin"
        [color]="color" [checked]="checked"
        (click)="onActiveHomeboxP(item.homeboxpackage_id, item.active)">
            {{item.active}}
        </mat-slide-toggle>
    </section>
</form>

Could someone suggest what might be wrong with this code? Thank you.

My Code Demo: DEMO

Updated Code: ts code:

this.activeHomeboxPForm = new FormGroup({
  'active': new FormControl(true, Validators.required),
  'homeboxpackage_id': new FormControl('', Validators.required)

});
  populateFormHomeboxP() {
    this.ws.homeboxPGetAll().subscribe(
      homeboxsp => {
        this.homeboxsp = homeboxsp.map((homeboxspp) => {
        this.activeHomeboxPForm.controls['active'].setValue(homeboxspp.active),
        this.activeHomeboxPForm.controls['homeboxpackage_id'].setValue(homeboxspp.homeboxpackage_id)
          console.log(homeboxspp)
          console.log(homeboxspp.active)
          console.log(homeboxspp.homeboxpackage_id)
          return new HomeboxP(homeboxspp);

        });
      }
    )
  }
  

html code:

  <tbody>
      <tr *ngFor="let item of homeboxsp; let i=index">
       <td> 
        <form [formGroup]="activeHomeboxPForm" class="col s12"> 
          <section class="example-section">
            <mat-slide-toggle  formControlName="active" class="example-margin" [checked]="item.active === '1'"> {{item.active}}
            </mat-slide-toggle>
          </section>
          </form>
      </td>
     </tr>
    </tbody>

In the provided image, everything looks fine on the console, but it doesn't display correctly in the HTML. When active = 1, it should be checked and when active = 0, it should be unchecked. Any ideas on how to resolve this?

Answer №1

It appears that you are using the same formControlName for all your sliders

To resolve this issue, consider assigning a unique control name to each slider

<div *ngFor="let item of homeboxsp; let index=i">
 <form [formGroup]="myform" class="col s12">
          <section class="example-section">
            <mat-slide-toggle formControlName="active-{{i}}" 

https://stackblitz.com/edit/angular-afrebm?file=app/app.component.html

Answer №2

In order to determine whether a slide is checked or not, you can use the [checked] property. So if you want your sliders to reflect the active property of your elements, you will need to implement something similar to the following code snippet:

<form [formGroup]="activeHomeboxPForm" class="col s12" materialize>
    <section class="example-section">
        <mat-slide-toggle formControlName="active" value="active"
        class="example-margin"
        [color]="color" [checked]="item.active"
        (click)="onActiveHomeboxP(item.homeboxpackage_id, item.active)">
            {{item.active}}
        </mat-slide-toggle>
    </section>
</form>

UPDATE

Check out the live demo here

Answer №3

Check out the complete working DEMO

Here's what was done: I modified `myform` to encompass all three slide-toggles and updated the `patchForm` function:

Take note of the changes in the template `[formGroup]="myform[i]"

@Component({
  selector: 'my-app',
  template: `  
    <div *ngFor="let item of homeboxsp; let i = index">
      <form [formGroup]="myform[i]" class="col s12">
          <section class="example-section">
            <mat-slide-toggle formControlName="active" value="active" class="example-margin" [color]="color" [checked]="item.active" (click)="onActiveHomeboxP()"> {{item.active}}
          </mat-slide-toggle>
          </section>
        </form>
   </div>
  `
})

Changes made in myForm declaration:

myform: FormGroup[];

constructor(public service: Service) {
...
    this.myform = [
      new FormGroup(
        {
         'active': new FormControl('', Validators.required),
         'homeboxpackage_id': new FormControl('', Validators.required)
        }),
      new FormGroup(
       {
         'active': new FormControl('', Validators.required),
         'homeboxpackage_id': new FormControl('', Validators.required)
       }),
      new FormGroup(   
        {
          'active': new FormControl('', Validators.required),
          'homeboxpackage_id': new FormControl('', Validators.required)
        })
      ];
}

Lastly, updates were also made in the `patchForm` method:

patchForm() {
  this.homeboxsp.forEach((val,i) => {
    this.myform[i].patchValue(
    {active: val.active == "1", homeboxpackage_id: val.homeboxpackage_id}
  )
});

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

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...

Encountering an error with RouterLink: 'frequency' property is undefined

In my Angular 4 project, I am encountering an issue with the following HTML code in my view: <p> You are on dashboard (first level); <a [routerLink]="['/second-dashboard', {frequency: frequency, datefrom: datefromparam, dateto: ...

Leveraging a ScrollView in an AbsoluteLayout with Angular Nativescript

I have developed a unique photo browsing app that allows users to swipe between pages to view different photos. Currently, I have implemented a working view for this feature. <ScrollView orientation="horizontal" ios.pagingEnabled="true" > <Stac ...

Typescript raises an error when providing a potentially null value (that is not null) to an unnamed callback function

When dealing with a property that starts as null, how can I pass it to an anonymous callback function expecting a non-null value without TypeScript throwing errors? I've tried wrapping the function call in an if statement to check for null at the cal ...

Implement the agmCircle method from angular-google-maps in a typescript file

Is there a way to retrieve the bounds of a circle once it has been changed? I noticed on that there is a "getBounds" method available. How can I access this method from my typescript file in order to log this data? This is how my html circle component cur ...

Encountering unproductive errors with custom editor extension in VS Code

I'm currently developing a custom vscode extension for a read-only editor. During testing, I encountered a rather unhelpful error message. Can anyone offer some insight on what might be causing this issue? 2022-11-25 11:36:17.198 [error] Activating ex ...

Issue with Node.js Command Line Interface

I'm a bit uncertain about this behavior, so please correct me if I'm wrong. I have developed an Angular 2/Ionic 2 application using the Node.js command prompt. Everything seems to be functioning correctly until I run the ng serve command. After t ...

``There is an issue arising from the interaction between EventEmitter and Custom

Working with an Angular 8.3.14 project. We have implemented an EventEmitter to communicate a string value to the parent component. Child Component Setup @Output() pepe = new EventEmitter<any>(); ngOnInit() { this.pepe.emit('pepe'); } ...

Engaging Angular Universal for internal API calls through Express

After researching numerous tutorials and guides on integrating SSR (server-side rendering) into existing angular CLI & Express projects, I successfully configured node with SSR. However, I encountered difficulties in making API calls. My goal is to have a ...

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

Step-by-step guide on implementing Form.create in TypeScript and Ant Design with function components

Having trouble compiling my form created using Form.create(). The error message I'm getting is: Argument of type 'FunctionComponent<MyProps>' is not assignable to parameter of type 'ComponentType<{}>'. Type 'Fu ...

Unclear on the usage of "this" in arrow functions?

After going through various discussions and articles on this topic, I find myself still perplexed about the meaning of this in arrow functions. I've been encountering run-time errors with a code snippet similar to the following: export class Foo imp ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

The development mode of NextJS is experiencing issues, however, the build and start commands are functioning normally

Just finished creating a brand new Next app (version: 12.0.7) using Typescript and Storybook. Everything seems to be working fine - I can successfully build and start the server. However, when I try to run dev mode and make a request, I encounter the follo ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could ...

Creating a Dynamic Example in Scenario Outline Using Typescript and Cypress-Cucumber-Preprocessor

I have a question that is closely related to the following topic: Behave: Writing a Scenario Outline with dynamic examples. The main difference is that I am not using Python for my Gherkin scenarios. Instead, I manage them with Cypress (utilizing the cypre ...

The application's functionality does not support the return type of `express-session

this.app.use( session({ // session configuration }) ); Encountering an error when passing the session configuration as shown above: Argument of type 'RequestHandler<ParamsDictionary, any, any, any>' is not assignabl ...

React component showing historical highchart data when navigating through previous and next periods

I developed this element to showcase a Highchart. It's utilized within a dashboard element that I access from an item in a list. It mostly works as intended, but not entirely. When I move to the dashboard for item A, everything functions correctly. H ...