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

How to pass data to the ng2-bs3-modal?

我有这个来自 *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>

点击 'Yes' 按钮时调用:

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

根据 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>

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

// 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');
    });
}