javascript - 如何在 Angular 2 中单击按钮时将数据从一个组件发送到另一个组件

标签 javascript typescript angular

所以我有以下代码在主页上显示表格,表格中的每一行都有两个按钮,“编辑”和“删除”。因此,当我单击“编辑”按钮时,模式将打开。现在我的问题是,我需要将特定员工单击按钮时的“员工 ID”传递给 .我怎样才能做到这一点?假设我有一个 id 为“101”的员工,想要编辑信息,如何将这个“101”传递给编辑模式组件点击按钮,以便我可以填充该信息的详细信息我的模态文本框中的员工?

@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]
    })

最佳答案

据我了解您的代码片段,您还有另一个组件可以打开模式来编辑您的员工 EditEmployeeModalComponent ,这可能是这个元素 <ops-editmodal ...

那么你可以做的是使用@ViewChild获取该组件的实例并调用它的公共(public)函数。

首先,您必须向组件添加一个 id <ops editmodal #myEditModal ...

然后在你的主要组件中:

export class MyComponent {

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

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

在你的 EditEmployeeModalComponent 中你有这个open(id:number)设置您的模型(或您用于表单的任何内容)并打开您的模式的函数。

希望这有帮助。

关于javascript - 如何在 Angular 2 中单击按钮时将数据从一个组件发送到另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37471652/

相关文章:

html - 如何将选定复选框的值作为数组发送到函数?

angular - 如何将 Angular Material 多选项限制为 N 项?

当元素进入视口(viewport)时,JavaScript/jQuery 添加类?

javascript - 如何将firebase数据库查询输出到VueJs页面

javascript - Redux reducer 不显示我的控制台日志并返回未定义

javascript - 在 Angular 2 和 Typescript 中创建日期扩展

javascript - 时刻格式详细日期作为日期对象

javascript - Angular : ng-repeat calculate data in view

angular - 如何监视构造函数中调用的方法?

javascript - 如何为数组中的每个元素绕过 SecurityTrustResourceUrl?