Tricks to access value from a Nativescript array of Switch elements when tapping a Button

Scenario:

In my project, I am using Nativescript 5.0 with Angular.

  1. The data is fetched from an API and displayed in customers.component.ts
  2. I am successfully rendering the elements based on the received IDs in customers.component.html
  3. When the user interacts with Switches and clicks the Save Button, it triggers the saveData() function
  4. However, in the saveData() function, I am encountering issues in reading which Switches are checked

I have implemented the following code snippet in customers.component.html to display the data without any errors:

<ListView [items]="_coursesmeta" [height] = "_coursesmeta.length == 0 ? 30 : _coursesmeta.length * 70" class="list-group">
    <ng-template let-result="item">   
        <GridLayout rows="auto auto" columns="* *" class="m-5" verticalAlignment="stretch">
            <Label class="h3 m-15" [text]="result.coursename" textWrap="true" row="0" col="0"></Label>
            <Switch [id]="'switch[' + id + ']'" class="m-15" row="0" col="1" ></Switch>                
        </GridLayout>
    </ng-template>
</ListView>

Is the usage of [id]="'switch[' + id + ']'" correct? And how can I determine if any of the Switches are checked?

The Switches are dynamically generated based on the data retrieved from the API.

**Edit - Adding the updated code below **

<ListView [items]="_coursesmeta" [height] = "_coursesmeta.length == 0 ? 30 : _coursesmeta.length * 70" class="list-group">
          <ng-template let-result="item">   
          <GridLayout rows="auto auto" columns="* *" class="m-5" verticalAlignment="stretch">
          <Label class="h3 m-15" [text]="result.coursename" textWrap="true" row="0" col="0"></Label>
         <Switch [checked]="result.selected" class="m-15" row="0" col="1" ></Switch>               </GridLayout>
     </ng-template>
    </ListView>

and the important section of the ts file looks like this

import { Component, OnInit } from "@angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { ActivatedRoute } from "@angular/router";

import { ObservableArray } from "data/observable-array";
import * as Permissions from "nativescript-permissions";
import { Coursemeta } from "../../shared/coursemeta.model";
import { CoursemetaService } from "~/app/shared/coursemeta.service";
var contacts = require( "nativescript-contacts" );

import { finalize } from 'rxjs/operators';

export class ContactManagerComponent implements OnInit {

    public constructor(private router: RouterExtensions, private route: ActivatedRoute, private _coursemetaservice: CoursemetaService) { }
    public _coursesmeta: ObservableArray<Coursemeta> = new ObservableArray<Coursemeta>([]); 

    ngOnInit(): void {                 
        this.callerName=this.route.snapshot.params["callerName"]; 
        this.callerNumber=this.route.snapshot.params["callerNumber"]; 
        this.input="";
        this._coursemetaservice.getCoursesmeta()
            .pipe(finalize(() => this._isLoading = false))
            .subscribe((coursesmeta: Array<Coursemeta>) => {
                this._coursesmeta = new ObservableArray(coursesmeta);       
                this.courseCount=this._coursesmeta.length;        
                this._isLoading = false;                 
            });        
    }

public ShowSelectedCourses()
{

    for(var i=0; i < this._coursesmeta.length; i++)
    {
        if(this._coursesmeta.getItem(i).selected == false)
        {
            alert("false = " + i);
        }    
    }
    alert("Saved ....");        
}
}

If a user slides the switch, I expect the selected property to be updated accordingly within the observable array.

I am successfully able to visualize the expected data without any API communication errors or rendering issues.

Answer №1

Various methods to achieve the desired outcome

  1. Implement the onSwitchChecked function

In your .ts file, handle the onSwitchChecked event

    import { Switch } from 'ui/switch';
    public onSwitchChecked(args) {
            const sortSwitch = <Switch>args.object;
            if (sortSwitch.id === 'id of your switch') {
                if (sortSwitch.checked) {
// Update the _coursesmeta or result.selected here.
    }
    }
  1. Utilize ngModel for your result.checked property e.g.

    <Switch [(ngModel)]='isSwitchChecked' (checkedChange)="onSwitchChecked($event)"></Switch>
    

In your .ts file

 public onSwitchChecked() {
            alert(this.isSwitchChecked);
        }

I have set up a playground where you can test the functionality here.

Answer №2

It is not advisable to use dynamic IDs. Additionally, when utilizing ListView, it cannot be guaranteed that all Switches or templates will remain active as you scroll through the content. The same element may be recycled with different data in order to maintain performance.

Instead, it is recommended to manipulate the data by binding the checked state of the Switch to a property within the data item. For instance:

<Switch [checked]="result.selected" class="m-15" row="0" col="1" ></Switch>

This approach allows for easily looping through the array to determine which items are selected.

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

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

A software error was encountered: Unrecognized or incorrect character detected

After running ng serve, I keep encountering the following error: An unhandled exception occurred: Invalid or unexpected token See "\mypc_path\AppData\Local\Temp\ng-Aij37E\angular-errors.log" for further details. The ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...

Creating a personalized event using typescript

I need help with properly defining the schema for an EventObject, specifically what should be included within the "extendedProps" key. Currently, my schema looks like this: interface ICustomExtendedProps { privateNote?: string; publicNote?: string; ...

The parameters provided in TypeScript do not align with any signature of the call target

In JavaScript, a function can be called with any number of parameters. If a parameter is not passed, it will default to undefined without causing an error. Below is a code snippet for reference: function test(a,b){ if(b){console.log(b)} else{console ...

Socket.io: The other client will only update when there is interaction happening

I am currently facing a challenge setting up a real-time application using socket.io in Angular and node.js. The application is not functioning as expected. When a client makes a new post, the other clients do not receive updates until there is some inter ...

Display the inputs from a reactive form in a different component

I am currently facing a situation where I have multiple components, such as component A, containing a reactive form. The data from these forms is stored in a central service. My goal now is to display a preview of this form in component B. However, upon na ...

"Data in Fusioncharts appears to be correctly formatted, but it is having difficulties

I am developing a financial analysis tool and I need to visualize stock data using fusion charts. Currently, my dataset includes stock values along with their respective dates: $scope.chartData = [ { "label": "2017-05-11 16:00:00", "value": "930.6" } ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

Encountering RxJS errors during the process of constructing an object using streams retrieved from Firebase

I am currently in the process of developing a template-driven form that involves multiple streams from Firebase. Despite my efforts, I keep encountering errors with the json pipe. The error message I receive is "Converting circular structure to JSON as ...

Modifying text input in Angular

I am working on an Angular form that includes a text input which I would like to be able to edit by clicking on the edit button. Within the form, there are 3 buttons available: edit, cancel (which discards changes), and save (which saves changes). When t ...

Utilizing Node.JS and Typescript to correctly define database configuration using module.exports

I am currently utilizing Mongoose in my node.js application, which is written in Typescript. The Mongoose documentation provides clear instructions on how to connect to their database like this, but I prefer to have the configuration stored in a separate ...

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

PrimeNG - Sticky header feature malfunctioning in the p-table

Hello there, I am currently using PrimeNG p-table which features both horizontal and vertical scrolling. My goal is to implement a sticky header for the table, so far I have attempted two methods: [scrollable]="true" scrollHeight="350px" ...

Refactor the fat arrow function in Typescript to maintain the bare function signature verification

When using AOT in Angular, it is necessary to rewrite all functions and reducers to not utilize arrow functions: An error occurred: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function o ...

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 ...

Determine the type of a function to assign to the parent object's property

Consider the following scenario: class SomeClass { public someProperty; public someMethodA(): void { this.someProperty = this.someMethodB() } public someMethodB() { ...some code... } } I need the type of somePropert ...

Filtering database results from an Angular component

I am currently working on an Angular component and I have a result variable in the .ts file that stores data retrieved from the database. My goal is to filter this result variable to display only 20 records and sort them by date either in ascending or de ...