Loop through the information retrieved from the alertController

I'm currently facing an issue regarding accessing data in my alert controller

let alert = this.alertCtrl.create({
  title: 'Edit Index',
  inputs:this.customIndexes,
  buttons:[
    {
      text: 'Cancel',
      role: 'cancel',
      handler: data=> {
        console.log('Cancel clicked');

      }
    },
    {
      text: 'Save',
      handler: data=>{
        console.log(data);
        /*for(let item of this.customIndexes)
        {
          this.customIndexes[item.name].value = data[item.name];
        }*/
        this.postEditedIndex(this.customIndexes);
      }
    }
  ]
});
alert.present();

When the user presses the save button, how can I retrieve the data?

My inputs are dynamic with the specified array structure like

customIndexes: { name: string, value: string, placeholder: string }[] = [];]

The function displays all fields that are populated into custom indexes, but how can I access them from the data object in the save button handler?

Answer №1

The issue you are encountering is related to the scoping of Object literals. To better understand this, take a look at this example: http://jsfiddle.net/1b68eLdr/76008/

class Test1 {
  name = "Name1";

  getName() {
    let test2 = {
      name: "Name2";
      getName2: ()=> {
        return this.name;
      }
    }
    return test2.getName2();
  }
};

let test1 = new Test1();
let name1 = test1.getName()

As a result, name1 will equal "Name2". This occurs because when you define a function within another object, it inherits that object's 'this' instead of the outer scope's 'this'. A common workaround for this is to store 'this' in a different variable (typically named self). For example: http://jsfiddle.net/5nup6cgx/

class Test1 {
  name = "Name1";

  getName() {
    let self = this; //<<<< NOTE HERE
    let test2 = {
      name: "Name2";
      getName2: ()=> {
        return self.name; //<<<< AND HERE
      }
    }
    return test2.getName2();
  }
};

let test1 = new Test1();
let name1 = test1.getName()

Therefore, what you likely intended to do was:

let self = this; //<<<<< NOTE HERE
let alert = this.alertCtrl.create({
  title: 'Edit Index',
  inputs:this.customIndexes,
  buttons:[
    {
      text: 'Cancel',
      role: 'cancel',
      handler: data=> {
        console.log('Cancel clicked');

      }
    },
    {
      text: 'Save',
      handler: data=>{
        console.log(data);
        for(let item of self.customIndexes)  //<<<<< AND HERE
        {
          self.customIndexes[item.name].value = data[item.name];  //<<<<< AND HERE
        }
        self.postEditedIndex(self.customIndexes);  //<<<<< AND HERE
      }
    }
  ]
});
alert.present();

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

Issue Arising from Printing a Custom Instruction in a Schema Generated Document

When dynamically adding a directive, the directive is correctly generated in the output schema. However, it seems to be missing when applied to specific fields. Here is how the directive was created: const limitDirective = new graphql.GraphQLDirective({ na ...

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

Excessive repetition in the style of writing for a function

When it comes to TypeScript, a basic example of a function looks like this: let myAdd: (x: number, y: number) => number = function ( x: number, y: number ): number { return x + y; }; Why is there redundancy in this code? I'm having trouble g ...

A method for transferring information stored in chrome.storage to a variable within an Angular component

How can I effectively assign data fetched from chrome.storage.sync.get to my Angular component's variable? Below is the code snippet of my component: export class KTableComponent implements OnInit { words: string[] = []; constructor() { } ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Discovering the data type from its textual representation

Is it possible for TypeScript to automatically determine the generic argument of assertTypeof based on the value of expectedType? I am looking for a way to use the function below without having to specify number multiple times. playable example type Typ ...

Cannot perform table inserts or creates with NestJS Sequelize functionality

I am currently in the process of setting up a small web server with a MySQL database. To achieve this, I am utilizing NestJs along with Sequelize. However, as I am still in the learning phase, I seem to be encountering an error: Within my database, I have ...

Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows: localjson.json { "Product" :{ "data" : [ { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }, { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } ] ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

What is the method in Angular 6 that allows Observable to retrieve data from an Array?

What is the method to retrieve data of an Array using Observable in Angular 6? ob: Observable<any> array = ['a','b','c'] this.ob.subscribe(data => console.log(data)); ...

Unleashing the Power of Firebase Service in Angular Components: A Guide to Effective Unit Testing

I am currently working on testing my Create-User-Component which relies on an Auth Service that includes methods like 'login, logout,' etc. The Auth Service imports both AngularFireAuth and AngularFirestore, and it is responsible for handling da ...

Unable to access the latitude property as it is undefined

I am completely puzzled by the appearance of this issue. This snippet shows my Google Map script: <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places,geometry"></script> Below you can see that I have defined lat ...

Return a potential undefined output

I am working with a variable called root which could potentially be undefined. Its value is only determined at runtime. const root = resolvedRoot || await this.fileSystem.getCurrentUserHome(); console.log('root.uri = ' + root.uri); The existenc ...

How should JSON files stored on the server side be properly utilized in Next.js?

Currently, I have a collection of JSON files that I expose through an API endpoint on my web application for global access. This allows different parts of the application to retrieve the data by sending a fetch request to itself... However, since this inf ...

Unable to locate the type definition file for 'jquery'

After updating my NuGet packages, I encountered an issue where I can no longer compile due to an error related to the bootstrap definition file not being able to find the jquery definition file within my project. Prior to the update, the directory structu ...