Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the edit modal component when the Edit button is clicked? For example, if the employee has an id of "101" and I want to edit their information, how do I pass this "101" to the edit modal component on button click in order to populate the details of that employee in text boxes within the modal?

@Component({
      selector: 'ops-employee',
      pipes: [],
      styles: [],
      template: `
          <ops-addmodal [(open)]="addEmployeeOpen" (check)="updateEmployeeList($event)"></ops-addmodal>
          <ops-editmodal [(open)]="editEmployeeOpen" [data]="editId" (check)="editEmployeeList($event)">
          </ops-editmodal>
          <div class="col-md-8 col-md-offset-2">
          <h1> Employee Info </h1>
          <hr>
          <button class="btn btn-lg btn-primary" (click)="addEmployee()">Add</button>
          <table class="table table-striped">
           <thead>
            <tr>
              <th>Name</th>
              <th>Age</th>
              <th>Role</th>
              <th>Actions</th>
            </tr>
           </thead>
           <tbody>
            <tr *ngFor = "#employee of employeeDetails">
              <td>{{employee.empName}}</td>
              <td>{{employee.empAge}}</td>
              <td>{{employee.empRole}}</td>
              <td>
              <button class="btn btn-sm btn-default" (click)="editEmployee(employee.empId)">Edit</button>
              <button class="btn btn-sm btn-danger" (click)="deleteEmployee(employee.empId)">Delete</button>
              </td>
            </tr>
           </tbody>
          </table>
          </div>
        `,
      directives: [AddEmployeeModalComponent, EditEmployeeModalComponent, ModalComponent]
    })

Answer №1

After carefully reviewing your code snippet, it appears that you have a separate component called EditEmployeeModalComponent that is responsible for opening the modal to edit the details of an employee. This component may be included in your code as <ops-editmodal ....

To interact with this component, you can utilize the @ViewChild decorator to access its instance and call a public function on it.

Firstly, ensure that you assign an id to your component by modifying the element to include

<ops-editmodal #myEditModal ...
.

In your main Component file:

export class MyComponent {

     @ViewChild('myEditModal')
     private _editModal: EditEmployeeModalComponent;

     editEmployee(employeeId: number): void {
         this._editModal.open(employeeId);
     }
 }

Within your EditEmployeeModalComponent, define the open(id:number) function. This function should update the model (or any form data) and display the modal window.

I hope these instructions are helpful for your project.

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

Challenges with cross domain iframes

I am trying to find a way to send a message from an iframe to the parent page at regular intervals, for example: Iframe Domain = www.abc.com Parent Domain = www.xyz.com I have looked into the following resources: Cross domain iframe issue If anyone ha ...

Dealing with file upload dialog using Selenium web automation

I am having difficulty managing the 'select files to load' dialog using Selenium WebDriver. Here is the HTML code snippet: <form class="upload"> <button class="btn" data-capture="" type="button">Browse</button> <inpu ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

deleting multiple items with checkbox selection in Angular 2

Can anyone provide the code for both the component and service to implement multiple deletion using checkboxes in Angular 2? I have only posted the HTML code, but I need assistance with the components and services as well. The current code allows single ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

Utilizing local storage functionality within AngularJS

I've been encountering challenges while trying to integrate local storage using ngStorage in my ongoing AngularJS project. Despite fixing what seems to be the root cause of data type problems and errors during debugging, issues persist. Here is the P ...

Choose everything except for the information determined by the search

Currently facing an issue with the select all functionality. I found a code snippet on this link but it's not exactly what I need. I want to modify the select all feature so that it is based on the search value. For instance, if I have a set of data ...

Executing `console.log()` in Windows 8 using JavaScript/Visual Studio 2012

Whenever I utilize console.log("Outputting some text") in JavaScript within Visual Studio 2012 for Windows 8 metro development, where exactly is the text being directed to? Which location should I look at to see it displayed? Despite having the "Output" pa ...

Utilizing custom hooks for passing props in React Typescript

I have created a unique useToggler custom hook, and I am attempting to pass toggle props from it to the button child in the Header component. However, when I try using toggle={toggle}, I encounter this error: Type '{toggle: () => void;}' is ...

What are some strategies for validating form fields in the Back-End and displaying them in Angular7?

My plan is to develop the backend of my app using Spring Boot and the frontend using Angular. I want to ensure the security of the form field information by validating it on the backend side. To get started, I created a model called Visitor.java with the f ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html: <button type="button" class="b ...

The Distinction between Object.assign and the simple assignment operation

Could you please explain the distinction between these two lines of code? Object.assign(otherObject, { someNewProperty: '' }); vs. otherObject.someNewProperty = ''; Also, which one of these methods is more efficient in terms of sp ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

Determining interface value based on the presence of another optional interface value

I am working with an interface that looks like this: export interface IButton { label: string; withIcon?: boolean; underlined?: boolean; selected?: boolean; iconName?: string; isLink?: boolean; href?: string; onCLick?: () => void; } My question ...

I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error. https://i.stack.imgur.com/SBPBf.png I also received the following error in the console https://i.stack.imgur.com/JBtbO.png ...

Checking forms for standard regulations with jQuery

Within my project, I have implemented multiple forms, where each form shares common fields like email, but also contains its own unique fields such as uniqueFieldA for Form A and uniqueFieldB for Form B. The challenge at hand is to develop a set of valida ...

Difficulty Encountered While Deploying Mean Stack Application on Heroku

I am embarking on my first journey of building a MEAN stack application, and I successfully created it locally. However, when attempting to host it on Heroku, things didn't go as planned. After researching online, I learned that both Angular and Expre ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...