Angular 7:如何在TS文件中隐藏模态框?表单保存后关闭模态框
Hey there! Let's sort out this modal closing issue for you. The problem with using data-dismiss="modal" on your save button is that it immediately closes the modal before your editExperience() save logic can finish executing—Bootstrap's native dismiss action interrupts the form submission flow.
Instead, we'll handle the modal closing manually in your TypeScript code after confirming the save operation is complete. Here's how to do it properly:
Step 1: Update Your Template
First, add a template reference variable to your modal (we'll use #editModal) and remove any data-dismiss attribute from your submit button (since we'll handle closing in TS):
<div class="modal fade" id="editExperienceModal" #editModal tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="listing-modal-2 modal-dialog"> <div class="submit_listing_box"> <h3>Experience</h3> <form #f="ngForm" class="form-alt" (ngSubmit)=editExperience()> <div class="row"> <div class="form-group col-md-6 col-sm-12 col-xs-12"> <label>Intitulé du poste </label> <input class="form-control" name="titre" [(ngModel)]="exp.titre" type="text" #titre="ngModel"> </div> <div class="form-group col-md-6 col-sm-12 col-xs-12"> <label> Entreprise </label> <input class="form-control" name="organisation" [(ngModel)]="exp.organisation" #organisation="ngModel" type="text"> </div> <div class="vfx-price-btn"> <button type="submit" class="purchase-btn pull-right"> Save</button> </div> </div> </form> </div> </div> </div>
Step 2: Implement Closing Logic in TypeScript
We'll cover two common scenarios depending on whether you're using ng-bootstrap (recommended for Angular projects) or native Bootstrap with jQuery:
Option 1: Using ng-bootstrap (Angular-Friendly Approach)
If you're using ng-bootstrap, use ViewChild to grab the modal reference and call its dismiss/close method after saving:
import { Component, ViewChild } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { Observable } from 'rxjs'; @Component({ // Your component metadata (selector, templateUrl, etc.) }) export class YourComponent { @ViewChild('editModal') editModal: any; exp: any = { titre: '', organisation: '' }; // Your experience object constructor(private modalService: NgbModal) {} editExperience() { // Execute your save logic (e.g., call an API) this.saveExperience().subscribe({ next: (response) => { console.log('Experience saved successfully!'); // Close the modal AFTER successful save this.editModal.dismiss('Save completed'); }, error: (err) => { console.error('Save failed:', err); // Handle error (e.g., show a toast notification) } }); } // Replace this with your actual API call private saveExperience(): Observable<any> { return new Observable(observer => { // Simulate API delay setTimeout(() => { observer.next('Success'); observer.complete(); }, 1000); }); } }
Option 2: Using Native Bootstrap with jQuery
If you're using plain Bootstrap (with jQuery included), use ElementRef to access the modal element and trigger Bootstrap's modal('hide') method:
import { Component, ViewChild, ElementRef } from '@angular/core'; declare var $: any; // Ensure jQuery and Bootstrap JS are loaded in your project @Component({ // Your component metadata }) export class YourComponent { @ViewChild('editModal') editModal: ElementRef; exp: any = { titre: '', organisation: '' }; editExperience() { // Execute save logic this.saveExperience().then(() => { console.log('Save successful!'); // Close the modal using Bootstrap's native method $(this.editModal.nativeElement).modal('hide'); }).catch(err => { console.error('Save failed:', err); }); } // Simulate async save private saveExperience(): Promise<void> { return new Promise(resolve => { setTimeout(resolve, 1000); }); } }
Key Notes
- Always close the modal after async operations: If your save is an API call (async), make sure to close the modal inside the success callback (like
subscribe'snextorPromise'sthen). This ensures the modal only closes once the save is confirmed. - Avoid mixing native Bootstrap dismiss with Angular logic: Using
data-dismissbypasses Angular's event flow, which is why your save wasn't executing before. Handling it in TS keeps everything aligned with Angular's lifecycle.
内容的提问来源于stack exchange,提问作者ghada

