Tips for ensuring your controls function properly and seamlessly when switching to another page

I utilized the instructions from this post to implement a slider. However, I encountered an issue with the controller when navigating to subsequent pages. While the controller functions correctly on the initial page, it duplicates the same values on the following pages. For example, if "Product 1" is active in the first line of page 1, it appears as active even on the second page, despite not being so. This pattern repeats across all pages. I suspect the problem lies within my ts code. DEMO Kindly review my code below:

  populateFormGPS() {
    this.ws.getAllGpss().subscribe(
      gpss => {
        this.gpss = gpss
        console.log(gpss)// all value arrive ok
        let controls = {
          'gps_id': new FormControl('', Validators.required)
        };

        for (let i = 0; i < this.gpss.length; i++) {
          controls['gps_actived-' + i] = new FormControl(this.gpss[i].gps_actived === 1, Validators.required)
        }
        this.acitveGPSForm = new FormGroup(controls);
        this.patchForm();
      }
    )
  }

  patchForm() {
    this.acitveGPSForm.patchValue({
      gps_id: this.gpss.map(x => x.gps_id),
    });
  }

Here is the HTML code snippet:

<div class="row">
  <div class="col s12 m2">
    <label class="col s12 label-control" style="padding: 0px">Rows on page</label>
    <select class="form-control input-sm" [(ngModel)]="rowsOnPage">
        <option [ngValue]="5">5</option>
        <option [ngValue]="10">10</option>
      <option [ngValue]="20">20</option>
    </select>
  </div>
   ...............
  .......... //Code truncated for brevity
 .............. 
</table>

If you have any insights on how to address this challenge, your assistance would be highly appreciated.

Thank you.

Answer №1

The reason for this issue is that your control names are tied to local indexes rather than IDs. This means that when you filter your rows to show n results per page, the row labeled as n will actually have an index of 0, causing it to share the same form control as the actual row 0.

To fix this problem, make the following changes in app.component.ts:

controls['active-'+i] = ...

Replace the above line with:

controls['active-'+this.homeboxsp[i].homeboxpackage_id] = ...

Next, in app.component.html, locate:

formControlName="active-{{i}}"

And replace it with:

formControlName="active-{{item.homeboxpackage_id}}" 

For a modified version of the code, visit this link.

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

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

ngOnChanges does not track changes made to the form

Currently, I am learning about ngOnChanges directly from the official documentation. However, I have noticed that it is not logging any changes in the HTML form. To address this issue, I made sure to import both FormsModule and ReactiveFormsModule into m ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

To successfully transfer a file (whether it be an excel or csv file) into a nodejs environment and then have it update in a mongodb database, follow

Can anyone guide me on how to upload a file, ensuring only Excel or CSV formats are accepted? I then need to read the file using Node.js and update it in a MongoDB database table. Technologies used: Angular 5 for front end, Node.js and MongoDB for backend ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

Tips for identifying unnecessary async statements in TypeScript code?

We have been encountering challenges in our app due to developers using async unnecessarily, particularly when the code is actually synchronous. This has led to issues like code running out of order and boolean statements returning unexpected results, espe ...

Hiding a div in Angular when selecting a language using ngx translate from a different component

I am currently working on an Angular application with version 16. I have integrated ngx translate for multiple languages support. Here is what I am trying to achieve: Within my header-component, there is a dropdown menu to switch between English and Spani ...

Utilizing a function in an infinite loop within *ngFor along with an asynchronous pipe for an HTTP call

Using a function in an *ngFor statement: @Component({ selector: 'foo-view', template: '<div *ngFor="let foo of loadAll() | async"></div>' }) export class FooComponent { loadAll(): Observable<Foo[]> { return ...

How can I verify the value of a class variable in TypeScript by using a method?

I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks: export abstract class ...

Preventing automatic focus on tabbable elements in Angular Material dialogs

The documentation states: Upon opening a dialog, the first tabbable element will be automatically focused. You have the option to specify which elements should act as tab stops using the tabindex attribute. I have not found any information in the documen ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

Creating custom components in AngularJS 2 allows you to define methods unique to each component. Want to learn

I created my component (A) by combining multiple html elements, but I have two questions. How do I define methods (such as get, etc.) on my component? I have tried @Output, @ViewChild, etc. but they are not working. I am looking for an alternative way ...

A guide on creating a LoopBack 4 REST API to fetch data from a MySQL database

I am currently diving into the world of Loopback 4. I have successfully created a model, repository, and datasource in connection with MySQL. This has enabled me to retrieve results from http://127.0.0.1:3000/myapi/{id}. In my initial setup, obtaining dat ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Utilize Typescript to generate an object that contains a partial interface

Seeking assistance with an issue. We are working with two interfaces: interface IUserEntity { Id: number; FirstName: string; LastName: string; } interface IUserEntityMethods { GetFullName(): string; } I am trying to create an object tha ...

Having trouble deploying my Angular application on Heroku

I have been attempting to deploy my Angular 6 application on Heroku. Despite building the project and following all deployment steps, I am encountering the following result on Heroku: Furthermore, the Heroku logs display the following: Upon testing the d ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Deciphering TS2345: "The argument supplied, known as 'typeof MyComponent', cannot be assigned to the specified parameter type"

I am facing an issue while attempting to integrate a Typescript React component with react-onclickoutside. The error message that I encounter is as follows: TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type &apo ...

The Validators.pattern in Angular fails to match when comparing two different versions

I encountered a unique scenario where I need to validate either a datetime format or an empty string. Both should be accepted inputs, but any malformed or incomplete datetimes should fail validation. myForm = this.form.group({ ... ts: [&apos ...

Adjust the color of the icon depending on the value

I am new to Angular2 and I'm looking for a way to dynamically change the CSS of an icon based on specific values. Here is the code in HTML: <li><i class="fa fa-check" [style.color]="'switch(types)'"></i>{{ types }}</l ...