Instructions on invoking a function when a button is clicked

I am attempting to trigger a dataUpdate function upon clicking the edit() button

I am striving to modify the record

Current Version:

  • Angular CLI: 10.0.6
  • Angular: 10.0.10

https://i.sstatic.net/4MR8P.png

registration.component.html

    <div>
      <button type="button" (click)="registration()">Submit</button>
      <div style="margin:5px;"></div>
      <button type="button" (click)="edit()">Edit</button>
    </div>

<h2>List Of Employee</h2>
<ag-grid-angular style="width: 1150px; height: 200px;"
                 class="ag-theme-balham"
                 [rowData]="elist"
                 [columnDefs]="columnDefs"
                 (rowClicked)='onGridRowClicked($event)'>
</ag-grid-angular>

registration.component.ts

  columnDefs = [
    { headerName: 'empid', field: 'empid' },
    { headerName: 'username', field: 'username' },
    { headerName: 'empaddress', field: 'empaddress' },
    { headerName: 'password', field: 'password' },
    { headerName: 'country', field: 'country' },
    {
      headerName: 'Edit',
      
      template: '<span><i class="fa fa-edit" data-action-type="edit"></i></span>',
    }
  ];

  onGridRowClicked(e: any) {
    if (e.event.target !== undefined) {
      let actionType = e.event.target.getAttribute("data-action-type");
      if (actionType == "edit") {

        this.rowData = this.myservice.getExistRecord(e.data.empid).subscribe((data: any) => {
          debugger
          console.log("inside get data from list 1")

          if (data.message == "GetSuccess") {

            //get data from the list
            debugger
            this.txtusername = e.data.username;
            this.txtempaddress = e.data.empaddress;
            this.txtpassword = e.data.password;
            this.txtcountry = e.data.country;

           //after retrieving the data then update a record
           var dataUpdate = function () {
              this.myservice.editExistRecord(e.data.empid, this.txtusername, this.txtempaddress, this.txtpassword, this.txtcountry).subscribe((data: any) => {
                console.log("Inside editExistRecord")
                if (data.message == "UpdateSuccessfully") {
                  this.list();
                }
              });
            }

            console.log("empid", e.data.empid);
            console.log("Edit Icon Clicked");
          }
        });
      }
      else if (actionType == "delete") {
        console.log("View delete action clicked");
      }
    }
  }
 
  edit() {
    console.log("inside edit button click event");
    //dataUpdate();//here I am trying to call dataupdate function
  }
e.data.empid                 //here, I am retrieving the empid which is why I am creating a function

how do I invoke this function?

var dataUpdate = function () {

When the user presses the edit() button, how can I call the dataUpdate function?

I have obtained the data from the list, but now I want to update it

If I write this code outside, empid becomes undefined

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

Answer №1

Here is a suggestion for refactoring your component:

onGridRowClicked(e: any) {
  if (e.event.target !== undefined) {
    let actionType = e.event.target.getAttribute("data-action-type");
    if (actionType == "edit") {

      this.rowData = this.myservice.getExistRecord(e.data.empid).subscribe((data: any) => {
        debugger
        console.log("inside get data from list 1")

        if (data.message == "GetSuccess") {

          //get data from the list
          debugger
          this.txtusername = e.data.username;
          this.txtempaddress = e.data.empaddress;
          this.txtpassword = e.data.password;
          this.txtcountry = e.data.country;
          this.empId = e.data.empid;
          this.dataUpdate();
          console.log("empid", e.data.empid);
          console.log("Edit Icon Clicked");
        }
      });
    }
    else if (actionType == "delete") {
      console.log("View delete action clicked");
    }
  }
}

//method to update a record after getting data
dataUpdate() {
  this.myservice.editExistRecord(this.empId, this.txtusername, this.txtempaddress, this.txtpassword, this.txtcountry).subscribe((data: any) => {
    console.log("Inside editExistRecord")
    if (data.message == "UpdateSuccessfully") {
      this.list();
    }
  });
}

edit() {
  this.dataUpdate();
}

Answer №2

To modify the form value, you must send a post or put request to the server after updating the data in the list!

For additional details, please refer to this demo.

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

Utilize the data structures and variables from one module to enhance the functionality

Currently, I am utilizing Babylonjs with Rollupjs in conjunction with typescript. https://i.sstatic.net/2L3bY.png When importing Babylonjs like so: import { ArcRotateCamera, Engine, SceneLoader, Vector3 } from "babylonjs"; I am able to access all the t ...

The issue I'm facing with the change handler for the semantic-ui-react checkbox in a React+Typescript project

Hey there! I'm currently facing an issue with two semantic-ui-react checkboxes. Whenever I try to attach change handlers to them, I end up getting a value of 'undefined' when I console log it. My goal is to retrieve the values of both check ...

After upgrading from Angular 7 to 12, the module './rest.service.interface' does not export 'RestService' (imported as 'RestService'), causing it to not be found

Hey everyone, I've been struggling with a problem for hours now and I can't seem to fix it. Here is the interface I'm working with: import { HttpClient } from '@angular/common/http'; import { Response } from '@angular/http&apo ...

What is the best way to properly include a parameter in my Angular 7 routing configuration?

I'm currently working on enhancing the detail section of my E-commerce platform. Here are the two paths I am using: { path: 'items', component: ItemListComponent}, { path: 'items/details/:id', component: ItemDetailComponent}, Wit ...

What is the method for utilizing a function's input type specified as "typeof A" to output the type "A"?

Check out this example from my sandbox: class A { doSomething() {} } class B {} const collection = { a: new A(), b: new B() } const findInstance = <T>(list: any, nonInstance: T): T => { for (const item in list) { if (lis ...

Currently attempting to ensure the type safety of my bespoke event system within UnityTiny

Currently, I am developing an event system within Unity Tiny as the built-in framework's functionality is quite limited. While I have managed to get it up and running, I now aim to enhance its user-friendliness for my team members. In this endeavor, I ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Is it possible to retrieve the selected DataList object in Angular 10?

I encountered an issue while creating an Input field with DataList. My goal was to retrieve the entire object associated with the selected option, but I could only access the selected value. Previous suggestions mentioned that DataList items should be uniq ...

Support for the percent sign in right-to-left languages

Imagine you have the following code snippet: <div dir="rtl"> test 50% </div> It currently displays as test 50%. However, according to this wiki page, for Arabic language it should be shown as %50 test, with the percentage sign before the n ...

Challenges with Angular 2 navigation paths

I'm currently facing a routing issue in my Angular 2 project. The app is quite small, featuring a PageNotFoundComponent, a HomeComponent for the index page, and an admin section. The admin section consists of a main AdminComponent, an AdminDashboardC ...

Establishing a custom variable within a recurring component in a form for the purpose of validation

For my booking form process, I have different sections for adults, pensioners, children, and infants. While they all share the same four inputs, each section also has some unique input fields based on the type of customer. To streamline the duplicate secti ...

The ng2-image-viewer does not support the newest versions of Angular (11 and above)

Encountering an issue with ng serve: Error message: ERROR in node_modules/ng2-image-viewer/index.d.ts:3:22 - error NG6003: Appears in the NgModule.exports of SharedModule, but could not be resolved to a NgModule, Component, Directive, or Pipe class. This ...

Steps for displaying a 404 page on a server-side rendered dynamic route following a client-side page transition

I'm currently developing a next.js project using Contentful as the Content Management System. My goal is to display a 404 page for a server-side rendered dynamic route after a client-side page transition. When I directly request the page (by entering ...

An issue arises when trying to access a resolved variable from UI router in a component

I am facing an issue with my UI router state that has a component attached to it: export const exchangeState = { name: 'exchange', url: '/exchange', component: ExchangeMainComponent, resolve: [ { tok ...

Occasionally, the translate.get function may return the key instead of the intended

I recently encountered an issue while working on a web application built with Angular 12 and ASP.NET Core 5. The application utilizes ngx-translate for internationalization, but I faced a problem with translating content in a new component that I added to ...

There is a potential for an object to be 'undefined' in TypeScript

My current project involves making a GET request from a mockAPI with the following structure: "usuarios": [ { "nome": "foo bar", "cpf": "213.123.123-45", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

DiscordJS bot using Typescript experiences audio playback issues that halt after a short period of time

I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing. Bel ...

Tips for customizing labels for boolean filters in DevExtreme data grid

We are looking to change the filter options in the status field (last row) from true/false to Active/Inactive. While there is a coding method to achieve this, we are struggling as we are using a table template. It seems like it should be a simple task but ...

Troubles with nesting ngFor in Angular 9 causing issues

I'm encountering an issue with utilizing nested ngFor loops in an Angular 9 application. The final ngFor loop mentioned in the code snippet below (line 12) appears to function sporadically, only on specific cycles of the main ngFor loop in the top row ...

Material-UI: Error thrown when attempting to pass props to makeStyles in React due to missing property 'X' on type '{}'

Currently experimenting with Adapting based on props, you can find more information here import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ // style rule foo: props => ( ...