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:

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

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

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

How can I convert duplicate code into a function in JavaScript?

I have successfully bound values to a view in my code, but I am concerned about the duplicate nested forEach loops that are currently present. I anticipate that Sonarcube will flag this as redundant code. Can anyone advise me on how to refactor this to avo ...

Failure of VSCode breakpoints to function properly with TypeScript npm linked package

I am developing a Next.js app using TypeScript and my .tsconfig file includes the following configurations: { "compilerOptions": { "baseUrl": "src", "experimentalDecorators": true, "target": & ...

Exploring the Connection with JSON-server

While creating a simulated API using json-server, I encountered an issue with passing a query. When utilizing _expand, I am able to display the parameters of a relationship, but it doesn't seem to work when the relationship is nested within a child. ...

What is the best way to relocate the styles folder to the src folder while using nextjs, typescript, and tailwind

I am currently working with Next.js using TypeScript and Tailwind CSS. My goal is to relocate the styles folder into the src folder. I have already updated the baseUrl in my tsconfig.json file to point to the src directory, but I encountered the following ...

What strategies should be employed when creating e2e tests that require a specific order of execution?

In the process of developing e2e tests for our angular app using Cypress.io, we are encountering a challenge. While we understand that tests should ideally not rely on each other, it seems challenging to avoid in a practical application. Consider a user ne ...

Error: Select dropdown placeholder malfunctioning

Even after trying numerous solutions from various forums, I am unable to make the placeholder display in my code. Maybe a fresh perspective can help spot what I might be missing. view image here I have experimented with using "" as the value, as ...

Access the Angular directive instance before it is actually rendered

Is it possible to access an Angular directive instance even if it has not been rendered yet? Let's say I have an app-component and a baz-directive. I want to be able to get the directive instance even if it is not currently shown or rendered in the D ...

Older versions of javascript offered the assurance of a promise

Working with TypeScript and the latest ECMAScript 6 feature Promise at the moment. I'm wondering if it's possible to use Promise even if my TypeScript code is compiled into an ECMAScript 3 js-file, considering that Promise wasn't available i ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

How to implement Dragula and Angular to enable draggable elements to be dropped in any position within their container?

I am in the process of developing a web application using Angular, which incorporates dragula. While the current drag and drop functionality works well for moving items within a designated "bag", I am seeking to enhance it with more advanced features. Is ...

Error in validating control groups in Angular 4

I'm currently working on setting up a standard form using Angular reactive forms. Below is the generic HTML code I have for input elements: <div class="form-input form-group" [formGroup]="group"> <div class="row"> <div clas ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

A guide to implementing typescript with Next.js getStaticProps

I have Next.js set up with the TypeScript feature enabled Currently, I am attempting to utilize the getStaticProps function following the guidelines outlined here: https://nextjs.org/docs/basic-features/typescript Utilizing the GetStaticProps type export ...

The TypeScript variable is automatically assigned the type 'any' since it does not contain a specified type annotation

Issue: The variable 'environment' is implicitly assigned the type 'any' because it lacks a specific type annotation and is referenced within its own initialization code. Code Snippet: export const environment = { production: fals ...

The process of uploading an Angular application to a server with an altered baseHref, resulting in the

I recently posted a question and had some discussions in the comments. Here is the link to the previous post for reference: Angular base href not showing up in URL In summary, my application works fine locally, with correct routing between localhost:4200/ ...

The Shell Application is not refreshing React HtmlElement Micro Front end

I am currently facing an issue when trying to inject the following React MFE into another Angular shell application. The MFE loads successfully the first time, but if it is hidden or removed from the DOM and then reloaded, it fails to load. Could you plea ...

Angular 4 CanActivateChild fails to function

I'm attempting to limit access to my route system by using the CanActivateChild feature. However, I've encountered an issue where the RouteGuard only works with the CanActivate function and not CanActivateChild. Here's a snippet of my routin ...