Automatically dismiss modal upon submission

In the process of implementing a CRUD operation, I am trying to automatically close the modal upon submission. Using data-dismiss on the submit button only closes the modal without executing the functionality. What I need is for the functionality to execute and then have the modal closed as well.

Below is the code snippet:

component.html

<!-- The Modal -->

<div class="modal" id="myModal">
<div class="modal-dialog">
  <div class="modal-content"> 

    <!-- Modal Header -->
    <div class="modal-header">
      <h4 class="modal-title">Create User</h4>
      <button type="button" class="close" data-dismiss="modal">&times;</button>
    </div>

    <!-- Modal body -->
    <div class="modal-body">
        <form  #createForm="ngForm" (ngSubmit)=" createUser()" >

          <div class="form-group" [class.has-error]="firstname.invalid  && firstname.touched">
            <label for="text">First name</label><br>
            <input type="text"  class="form-control" [(ngModel)]="user.user.first_name" name="firstname" required #firstname="ngModel" >
            <span class="help-block" *ngIf="firstname.invalid && firstname.touched">
                *First Name is required
              </span>
          </div>
          <div class="form-group" [class.has-error]="lastname.invalid  && lastname.touched">
            <label for="text">Last name</label><br>
            <input type="text"  class="form-control" [(ngModel)]="user.user.last_name" name="lastname" required #lastname="ngModel">
            <span class="help-block" *ngIf="lastname.invalid && lastname.touched">
                *Last Name is required
              </span>

          </div>
          <div class="form-group" [class.has-error]="email.invalid  && email.touched">
            <label for="text">Email</label><br>
            <input type="text" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" [(ngModel)]="user.user.email" name="email" required #email="ngModel">
            <span class="help-block" *ngIf="email.invalid && email.touched">
              *Email is required
            </span> <br>
            <span class="help-block" *ngIf="email.errors?.pattern">
              *Invalid pattern
            </span> 
          </div>

              <div class="form-group" [class.has-error]="role.touched && role.invalid">
                <label for="role">Role</label>
                <select id="role" name="role"
                       class="form-control" required [(ngModel)]="user.role" #role="ngModel" >
                  <option *ngFor="let role of roles" [value]="role.name" >
                    {{role.name}}
                  </option>
                </select>
                <span class="help-block"
                    *ngIf="role.touched && role.invalid">
                     *Role is required
                </span>
            </div>  

          <button type="submit"  [disabled]="createForm.invalid" class="btn btn-primary">Submit</button>
        </form>
    </div>


  </div>
</div>

component.ts

//Create User
createUser() {
var data= this.user_data;
 let user:any = {};
   user["username"] = this.user.user.email
   user["first_name"] = this.user.user.first_name
   user["last_name"]= this.user.user.last_name
   user["email"]= this.user.user.email

   this.userData["user"] = user
   this.userData["role"] = this.user.role
   console.log(this.userData, "sending data")
   this.Authentication.create_user(this.userData).subscribe(res=>{
//  data.push(res);
   this.getUsersFromServices();  
//  console.log(this.getUsersFromServices);
   console.log('data received after creating user',res);   
   },
   err =>{
  console.error("Error creating user!"); 
// return Observable.throw(Error);

})

}

Answer №1

If you're looking to streamline your form creation process, I suggest utilizing Angular's reactive forms. By structuring your form logic within the component class, it becomes much easier to refactor and implement changes. Here is a simplified example to guide you through the process:

<div class="popup" #myPopup>
  <form #createForm="ngForm" (ngSubmit)="submitForm()">
    <div>
      <label for="text">Full Name</label><br>
      <input type="text" formControlName="name" required>
    </div>
  </form>
</div>

In your component class, initialize the form as shown below:

export class MyFormComponent {
  myForm: FormGroup;
  ViewChild('myPopup') popup: ElementRef;

  constructor() {
    this.myForm = new FormGroup({
      name: new FormControl(null),
      email: new FormControl(null)
      // Add more fields as needed
    })
  }

  submitForm() {
    const formData = {
      data: this.myForm.value,
      role: // Extract role information here
    }
    this.MyService.saveData(formData).subscribe(res => {
      this.popup.nativeElement.modal('hide');
    });
  }
}

By using ViewChild, you can access the modal element and trigger Bootstrap's .modal('hide') function seamlessly.

Answer №2

To manage the display of a modal, you can set up a global variable in your TypeScript file:

public showModal: boolean = false;

Then, use this variable as a condition for the modal HTML element:

<div class="modal" id="myModal" *ngIf="showModal">
  ...
</div>

The modal will only be visible when the variable is true. Make sure to update the variable to true in the click method that triggers the modal.

Finally, reset the variable to false at the end of the method that closes or submits the modal:

submitForm() {
  ...
  this.showModal = false;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to incorporate SignalR into a TypeScript project?

Working on an asp.net mvc 4.5 project with typescript in the client side, I successfully installed and configured signalR on the server side. To integrate it into my project, I also installed signalr.TypeScript.DefinitelyTyped with jquery. In my typescrip ...

Using TypeScript to return an empty promise with specified types

Here is my function signature: const getJobsForDate = async (selectedDate: string): Promise<Job[]> I retrieve the data from the database and return a promise. If the parameter selectedDate === "", I aim to return an empty Promise<Job[] ...

Customizing event typings for OpenTok in Typescript

Currently, I am working on integrating chat functionality using the 'signal' events with the OpenTok API. Here is my event listener that successfully receives the signal: // Listen for signal CHAT_MESSAGE sess.on('signal:CHAT_MESSAGE', ...

Angular: The unexpected emergence of certificate issues and the ensuing challenges in resolving them

After completing the first two chapters of Google's Tour of Heroes, I repeated the process 21 times without any major issues. However, when attempting to run it for the 22nd time on the same machine and with the same Visual Studio setup, I encountered ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...

What is the process for extracting the paths of component files from an Angular ngModule file?

I've been on the lookout for automation options to streamline the process of refactoring an Angular application, as doing it manually can be quite tedious. We're working on reducing our app's shared module by extracting components/directive ...

What is the significance of the error message "Surprisingly in Angular Zone despite expectations"?

Ever since upgrading from Angular 2 RC4 to RC5, I've been encountering this error. Although it doesn't seem to impact the application's functionality, it keeps appearing in the console and may draw attention away from other errors. Does any ...

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

React onClick event image attribute is unique because it allows for interactive

Is there a way to dynamically add the onClick attribute to an image, but have the click event not working? //Code const parser = new DOMParser(); const doc = parser.parseFromString(htmlContent, "text/html" ); const imageDa ...

The presence of a default value within an Angular ControlValueAccessor triggers the dirty state due to

My task is to create dynamic Input components for a template driven form using a directive. The default value of the Input component should be set by the component itself. However, I encountered an issue where setting a default value automatically marks t ...

Indicate the location of tsconfig.json file when setting up Cypress

Having trouble integrating Cypress with Typescript? I've encountered an issue where Cypress is unable to locate the tsconfig.json file I created for it. My preference is to organize my project with a custom directory structure, keeping configuration f ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

Using TypeScript to assign string array values to object properties

I am working with a string array: values: string['myName', 'myLastname', 'myAge'] and my goal is to assign each value to a property of an object like this: myModel={name:'', lastname:'', age:''} o ...

Adjusting the height of an Angular CDK virtual scroll viewport based on dynamic needs

Currently, I am developing an Angular table with the cdk Virtual Scroll feature. Is there a method to adjust the scroll viewport's height dynamically? While the standard style property works, I am encountering difficulties setting the value using ngSt ...

Error: The AppModule is missing a provider for the Function in the RouterModule, causing a NullInjectorError

https://i.stack.imgur.com/uKKKp.png Lately, I delved into the world of Angular and encountered a perplexing issue in my initial project. The problem arises when I attempt to run the application using ng serve.https://i.stack.imgur.com/H0hEL.png ...

Leveraging Angular OpaqueToken for Injecting Config Object Does Not Display Type Errors

When using an OpaqueToken to inject a config object into the application in Angular, I followed the documentation and was able to successfully DI the config into a component and retrieve values. However, I encountered an issue when trying to enforce type c ...

React Typescript: Turn off spellchecking

Struggling to turn off spell check for typescript <form> <input type='text' name='accountName' ref={accountName} onChange={checkName} spellCheck='false' // <====== Disable spellche ...

Using TypeScript with ReactJS

While working on a form using React-select, I encountered an issue when trying to pass parameters to a function. The error message returned was: Expected 1 arguments, but got 0.ts(2554) index.tsx(31, 31): An argument for 'selectRef' was not pr ...

Dealing with errors from APIs in a React TypeScript application

Currently, I am in the process of learning React and Typescript by creating a demo application. This app sends a request to the API located at in order to retrieve postcode information and display details about a specific location based on the entered pos ...

CSS: Achieving Full Container Width Text with Respect to Another Container's Height

Hello, I am facing a very specific issue that I can't seem to resolve: I have two containers (ion-card) and I want them to always be the same height. I was able to achieve this by following the solution provided here: https://i.sstatic.net/he8O7.png ...