Utilize the identical function within the reducer for numerous mat-slide-toggle and checkboxes in component.html

I'm currently diving into the world of Angular and ngrx while tackling a project focused on enabling users to create forms. In this project, users can add various form elements (such as labels, text fields, dropdown menus, checkboxes, etc.) from a sidebar. Each generated form element is accompanied by two buttons - one for deleting and another for options. My task now involves integrating a slide-toggle/checkbox alongside these buttons, as depicted in the image below:

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

======================================================

component.html

<!-- Sidebar for adding form elements -->

<div id="add-element-div">
    <button mat-icon-button matTooltip="Label"
            (click)="store.dispatch(createAction.editorAddLabel(currentPageNumber))">
      <mat-icon class="color">label</mat-icon>
    </button>
.....
</div>

<!-- Option buttons for every element -->
<div class="ElementOptionButtons">

<button mat-icon-button
 (click)="store.dispatch(this.createAction.editorRemoveElement(currentPageNumber,
 currentForm.pages[currentPageNumber].pageElements.indexOf(FormularElement)))"
 matTooltip="Delete">
 <i class="material-icons">delete</i>
</button>
....


<!-- Toggle-slider/checkbox -->


  <mat-slide-toggle
    *ngIf="FormularElement.type!=='label'"

    (change)="store.dispatch(createAction.editorAddAsRequired(currentPageNumber,
    currentForm.pages[currentPageNumber].pageElements.indexOf(FormularElement)))" 
    matTooltip="Pflichtfeld">
    <p>{{i}}</p>
  </mat-slide-toggle>

</div>

reducer.ts

   case fromEditorForm.EDITOR_ADD_AS_REQUIRED: {
      const changedState = JSON.parse(JSON.stringify(state));
      console.log('Reducer: mark as required');
      console.log(" element: " + action.elementIndex + " pageNumbeR: " + action.pageNumber );
      //changedState.form.pages[action.pageNumber].pageElements[action.elementIndex].required=true;
      return changedState;
    }
      return changedState;

component.ts

export class EditorComponent implements OnInit {
  public chosenBusinessType;
  public currentForm: Form;
  public currentPage: FormularPage;
  public currentPageElements: FormElement[];
  public currentPageNumber;

  public loadedForms: Form[];

  public createAction = new ActionFactory();

  constructor(private store: Store<fromStore.GeneratorState>,
              private formsService: FormsService,
              private route: ActivatedRoute) {

    this.store.select(fromStore.getLoadedForms).subscribe((forms) => {
      this.loadedForms = forms.entities;
    });
  }

  ngOnInit() {
    this.currentPageNumber = 0;
    this.route.params.subscribe(params => {
      if (params.id === 'newForm') {
        console.log('EDITOR: Aufgerufen zum Erstellen eines neuen Formulars');
        this.currentForm = new Form();
      } else {
        console.log('EDITOR: Aufgerufen zum Bearbeiten eines existierenden Formulars');
        for (const form of this.loadedForms) {
          if (form.id === params.id) {
            this.currentForm = form;
          }
        }
      }
      this.store.dispatch(this.createAction.editorChangeForm(this.currentForm));


      this.store.select(fromStore.getFormInEditor).subscribe((object) => {
        this.currentForm = object.form;
        this.chosenBusinessType = this.currentForm.businessType;
      });
    });
  }

======================================================

My Objective

The goal is to have each element marked as required when the corresponding slide-toggle/checkbox is checked. I am aiming to implement a single method that handles all sliders on the (change) event.

The Issue at Hand

Upon trying to toggle the slider switches, I noticed that either all sliders switch to true or nothing happens (depending on my approach). Introducing a (change) function in the HTML causes the issue of affecting all sliders or none. When omitted, the targeted slider toggles correctly, but not others.

Attempts Made So Far

To ensure uniqueness, an index was added to each slider (as observed in the picture above). Clicking on the sliders logs the correct form element, yet the sliders fail to be toggled upon interaction.

In seeking solutions, I explored similar questions on Stack Overflow and Google. One question that came close to mine involved toggling sliders using different methods, unlike my scenario with ngrx where the problem seems related to two-way binding.

Next Steps

I am considering creating a function in reducer.ts that adds a new FormElement following the addition of an element to FormElement in component.ts. However, I remain uncertain about whether this aligns with best practices.

=======

Being relatively new to Angular and ngrx, I am open to any essential basics that may have been overlooked. Should more code or details be needed, feel free to request updates for the post.

Answer №1

Managed to figure out the solution on my own.

The entire code block is nested within a div that contains an ngFor loop. I then incorporated an ngModel for the slider, in addition to introducing an elemntSlider as a model for the entire form model, which is now included (the elementSlider) with every new element added to the form.

         <mat-slide-toggle
          *ngIf="FormularElement.type!=='label'"
          [(ngModel)]="FormularElement.elementSlider"
        </mat-slide-toggle>

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

Step-by-Step Guide: Customize the Background Color in an Angular 4 Select Dropdown Based on the Selected Option

I'm facing a challenge in setting the background color of a select element based on the color attribute of its currently selected option. I'm using Angular 4 for this task. An example of what I am attempting to accomplish is shown below: <se ...

The JSON representation is not appearing for the newly introduced nested components

Building a nested component within another component and implementing two-way binding for dynamically added field values using the JSON pipe in the view. However, encountering an issue where the newly added values are not reflected in the JSON view. If yo ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

Is it possible to define data types for the global context in cucumber?

Embarking on a fresh cucumber-selenium project in Typescript, I am eager to keep the Driver in the world context. However, following the method suggested here, I encounter an issue where the Driver type remains inaccessible to step definitions. This means ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

Tips for packaging a Node TypeScript/JavaScript library using Webpack

I am currently working on a Node project with the following setup: Written in Typescript Using Webpack and ts-loader for bundling Targeting Node.js +-proj/ +-src/ |-file1.ts |-file2.ts |-file3.ts |-... |-package.json |-webpack.confi ...

What is the method for including a TabIndex property in a JSON file?

https://i.sstatic.net/ISi72.png I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Angular 2: Making POST Requests

I have encountered a peculiar issue with Angular 2 HTTP post requests. public post(_ApiUrl: string, _Body: string): Promise<any> { let token = this.storage.getauthToken(); const headers = new HttpHeaders().set("Content-Type", "application/j ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

I'm having trouble getting Remix.run and Chart.js to cooperate, can anyone offer some guidance?

I've encountered a challenge with Remix.run and chart.js (react-chartjs-2) when attempting to display the chart. I followed the documentation and installed the necessary dependencies: react-chartjs-2 and chart.js. Here's the snippet from my pac ...

Leverage a custom server (such as NestJS) within NextJS to dynamically render targeted pages

I am experimenting with using NestJS as a custom server for NextJS, following the instructions in this article. Here is a simplified version of the code: @Controller('/') export class ViewController { @Get('*') async static(@Req() r ...

Redux Saga effect does not have a matching overload for this call

Encountering an error in my Redux Saga file, specifically when using the takeLatest() Saga effect. TypeScript is throwing the following error: (alias) const getMovies: ActionCreatorWithoutPayload<string> import getMovies No overload matches this call ...

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

Tips for resolving the 'JSX is not defined no-undef' error post TypeScript 4.4.2 update

Upon upgrading to TypeScript 4.4.2 from TypeScript 3.8.2, I have encountered numerous errors such as error 'x' is not defined no-undef. For instance, one of the errors is error 'JSX' is not defined no-undef. Upon closer inspection, most ...

Passing parent form controls from an Angular 4 FormGroup to a child component

I have implemented Angular Reactive Forms FormGroup and FormArray in my project. The issue I am facing is related to splitting my form fields into child components and passing the parent form controls to them. I expected this to be a straightforward proces ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Can Angular reactive forms be used to validate based on external conditions?

Currently, I am exploring Angular reactive forms validation and facing an issue with implementing Google autocomplete in an input field: <input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName ...

Dynamic value for href in div using Angular

Implementing a dynamic submenu using Angular is my current project. At the moment, I have set the href attribute with hardcoding as shown below: <ng-template #preSelectionMenuItem let-preSelections="preSelections"> <div class=' ...