首页 > 解决方案 > 从 ng-bootstrap Modal 删除后用新数据重新加载组件

问题描述

我正在尝试理解一些概念,并想看看是否有人可以提供帮助。我有一个 ng-bootstrap 模式,显示一些从父组件中进行的 API 调用输入的信息。基本上,我在这个模式中显示数据,我可以点击删除路线来删除一些记录。这一切都很好,但我遇到的问题是当我关闭模式时,我希望父组件刷新而不显示刚刚从模式中删除的记录,所以基本上再次运行请求并更新信息,但我不知道如何做到这一点。我相信通常这可以通过事件发射器来完成,但我被卡住了,因为我是从模态和使用 ng-bootstrap 执行此操作的。任何帮助理解这一点将不胜感激!

这是我的代码:

应用程序.html:

<div>
  <ul>
    <li *ngFor="let user of users">{{user.first_name}}</li>
  </ul>
    <button (click)="openFormModal()" class="btn btn-primary btn-sm">view more</button>
</div>

应用程序.ts:

export class AppComponent {
  users: any;

  constructor(private api: ApiService,
    private modalService: NgbModal) {}

    ngOnInit() {
    this.getUsers();
  }

openFormModal(){
    const modalRef = this.modalService.open(DetailsModalComponent);
    modalRef.componentInstance.users = this.users;

    modalRef.result.then((result)=> {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });
}

  getUsers() {
    this.api.getUsers().subscribe(data => {
        this.users = data;
    })
  }  
}

详细信息-modal.html:

  <div class="modal-header">
  <h4 class="modal-title">Modal Title</h4>
  <button type="button" class="close" aria-label="Close"
   (click)="closeModal()">
  </button>
</div>
<div class="modal-body">
  <p *ngFor="let user of users">{{user.first_name}} <span (click)="deleteUser(this.user.id)" style="cursor: pointer">DELETE</span></p>
</div>
<div class="modal-footer">
  <button (click)="closeModal()">
    Close Clicked
  </button>
</div>

详细信息-modal.ts:

@Component({
  selector: 'app-details-modal',
  templateUrl: './details-modal.component.html',
  styleUrls: ['./details-modal.component.css']
})
export class DetailsModalComponent implements OnInit {
  @Input() users;

  constructor(
    public activeModal: NgbActiveModal,
    private api: ApiService
  ) {}

  ngOnInit() {
  }

  fetch() {
    this.api.getUsers().subscribe(data => {
      this.users = data;
    })
  }

  closeModal() {
    this.activeModal.close()
  }

  deleteUser(id) {
    this.api.deleteUser(id).subscribe(data => {
      this.fetch();
    })
  }

}

标签: javascriptangularmodal-dialogng-bootstrappage-refresh

解决方案


显然从this GitHub post,你可以做到这一点

modalRef.result.then(
  () => {
     console.log("Close button clicked");
     // actions
  },
  ()=> {
     console.log("Close icon clicked or backdrop clicked");
     // actions
});

Stackblitz:https ://stackblitz.com/edit/angular-ey8hkm


推荐阅读