如何将数据传递给ng2-bs3-modal?

时间:2017-01-23 08:59:43

标签: angular ng2-bootstrap

我有一个来自* ngFor的片段,所以它被多次填充。每个配置文件都有一个唯一的ID,我想在我使用此按钮时将其删除:

<a data-toggle="modal" data-target="#deleteProfile" (click)="deleteProfile.open()" role="button" style="color:red;"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</a>

html模式:

    <modal #deleteProfile>
  <modal-header [show-close]="true">
    <h4 class="modal-title">Delete Profile</h4>
  </modal-header>
  <modal-body>
    <div class="text-center">
      Are you sure you want to delete this profile?
    </div>
  </modal-body>
  <modal-footer>
    <div class="control-group confirm-buttons">
      <div class="row text-center">
        <div class="col-md-6">
          <button type="button" class="btn btn-cancel" data-dismiss="modal" (click)="closeDeleteProfile()">No</button>
        </div>
        <div class="col-md-6">
          <button type="button" class="btn btn-confirm" (click)="deleteProfile()">Yes</button>
        </div>
      </div>
      <div class="col-md-12 text-center">
        <small>This is the footer</small>
      </div>
    </div>
  </modal-footer>
</modal>

单击“是”按钮时调用此方法:

deleteProfile(id: string) {
this.modalDeleteProfile.dismiss();
this.profileService.delete(id)
  .subscribe(
    //  data =>  console.log(data),
    //  error =>  console.log(error)
  );
this.router.navigateByUrl('/dashboard');
}

我如何将id传递给模态,以便上面的代码获取id以删除配置文件?

这是我正在使用的模式:https://github.com/dougludlow/ng2-bs3-modal

1 个答案:

答案 0 :(得分:3)

根据OP在评论中的要求,以下是该问题的替代解决方案。可以通过在组件中添加额外的方法来解决该问题。

你说你有一个* ngFor,它遍历一个数组。不要使用按钮直接打开模态,而是打开一个方法,它会传递配置文件的ID,因此您的迭代可能如下所示:

<table>
  <tr *ngFor="let profile of profiles">
    <td>{{profile.id}}</td>
    <td>{{profile.name}}</td>
    <td><button (click)="openDeleteModal(profile.id)">Delete Profile</button</td>
  </tr>
</table>

然后,在我们将id绑定到组件中的局部变量之后,openDeleteModal - 方法将打开模态窗口。

// declare an extra variable that can be used in deletion
idForDeletingProfile;

openDeleteModal(id) {
  // here we bind the chosen id, so that we can use it in your delete-method
  this.idForDeletingProfile = id;
  this.modalDeleteProfile.open()
}

然后我们有你的模态,我缩短了它只显示按钮:

<modal #deleteProfile>
  <!-- more code here -->
     <button type="button" class="btn btn-cancel" data-dismiss="modal" (click)="closeDeleteProfile()">No</button>
     <button type="button" class="btn btn-confirm" (click)="deleteProfile()">Yes</button>
  <!-- more code here -->
</modal>

如果用户点击deleteProfile() - 按钮,我们之前已将所选的ID存储在idForDeletingProfile中,现在可用于删除。

deleteProfile() {
  this.modalDeleteProfile.dismiss();
  // use the local variable here!
  this.profileService.delete(this.idForDeletingProfile)
    .subscribe( data => {
       console.log(data);
       this.router.navigateByUrl('dashboard');
    });
}
相关问题