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

How do you implement an asynchronous validator for template-driven forms in Angular 2?

I have created a custom directive for my asynchronous validator: @Directive({ selector: '[validatorUsername]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ValidatorUsernameDirective, multi: true }] }) export class ValidatorUsern ...

Is there a way to target the mat-icon element using the icon's name in CSS

I have a group of mat-icons that are automatically generated, meaning I cannot assign them ids or classes. The only way to distinguish between them is by their names: <mat-icon role="img">details</mat-icon> <mat-icon role="img ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Is there a way to alter the stroke color of an SVG icon in Angular 2 or 4 by clicking on it?

Having trouble with this code, can someone provide a solution? This is the SVG icon code: <svg id="Home" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52.28 43.49"> <defs> <style> .cls-1{fill:none;stro ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

The Freemode feature in SwiperJS is not functioning properly when used with React TypeScript

Having a slight issue with SwiperJS. Using version 10.1.0 and the following code : import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; export default function Discover() { return ( <> ...

Ways to duplicate package.json within a Dockerfile

My issue revolves around the challenge I am facing while attempting to copy my package.json to the Dockerfile context. Below is a representation of my file structure: src - apps -- api --- Dockerfile - docker -- tcp --- docker-compose.yml - package.json H ...

Creating a dynamic component in Angular using the ng-template approach

Exploring Components using ng-template @Component({ template: ` <div>Welcome to the Component!</div> <ng-template #contentTemplate> <div>This is the template content</div> </ng-template> `, }) expo ...

Encountered an issue when deploying on CF: "ERROR The serve command must be executed within an Angular project, however a project definition could not be located."

I need to set up my Angular Application on Cloud-Foundry. Here is the package.json file currently located in the dist folder: { "name": "showroom-app", "version": "0.0.0", "engines": { "node" ...

Unique messages are provided for each validation check

Currently, I am delving into Angular 2 and working on setting up a basic registration form with some essential validations. The input field has three validations: required, minLength, and maxLength. However, I want to display different validation messages ...

In Deno, it is possible to confirm that a variable is an instance of a String

I'm having trouble asserting instances of string in Deno: import { assertInstanceOf } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2642405050405e445e59445e">[email protected]</a& ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

Is there a new implementation of "ComponentFactoryResolver deprecated" with missing attributes?

Since Angular 13, the usage of ComponentFactoryResolver has been deprecated. Finding a suitable replacement is proving to be a challenge as the old rootSelectorOrNode parameter is no longer available in the new solution. I have a requirement to dynamicall ...

Using dictionary keys as valid property values

I have put together a dictionary like so: const iconTypesDictionary: { [key: string]: IconPrefix } = { solid: 'fas', regular: 'far', light: 'fal', } My goal is to be able to utilize the keys of this dictionary as potent ...

Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's. I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4). Let's delve into some code snipp ...

Dealing with Angular: unresolved promise error occurring with the utilization of pipe and mergemap

Recently, while working on my Angular 6 project, I came across the concepts of pipe and mergemap, which intrigued me. Essentially, I have a scenario where I need to allow the user to choose between two different CSV files stored in the assets folder. The d ...

Deactivate multiple textareas within a loop by utilizing JQuery/Typescript and KnockoutJS

I am working on a for loop that generates a series of textareas with unique ids using KO data-binding, but they all share the same name. My goal is to utilize Jquery to determine if all the textareas in the list are empty. If they are, I want to disable al ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

Implement a concealed identification field with React-Admin within a React Native application

I'm currently working on incorporating the SimpleFormIterator from the React-Admin module in order to generate a list of child records within a parent record edit form. After setting up the SimpleFormIterator component with all the necessary details ...

Stop receiving notifications for channel events in Stream with the GetStream.io Chat API

I'm having trouble understanding how to stop listening for channel events in JavaScript using the Stream Chat API. According to the documentation: // remove the handler for all "message.new" events on the channel channel.off("message.new", myChanne ...