Sending a form via Angular Dialog Template

While attempting to submit a form from a dialog, I encountered an issue where form.value is showing as null. I'm not sure what might be causing this. Below is a snippet of the code along with a DEMO for reference.

HTML

<div>
<button mat-raised-button (click)="openDialog()">Pick one</button>
</div>

  <ng-template #callAPIDialog>
        <form #userForm="ngForm" (ngSubmit)="onSend(form.value)">
        <h2 matDialogTitle>Add Organization</h2>
        <mat-form-field>
            <input matInput [(ngModel)]="organisationName" placeholder="Your organization" [ngModelOptions]="{standalone: true}">
            <input matInput [(ngModel)]="enabled" [(value)]="Y" [ngModelOptions]="{standalone: true}">
          </mat-form-field>
        <mat-dialog-actions align="end">
            <button mat-button matDialogClose="no">Cancel</button>
            <button type="submit" mat-button matDialogClose="yes">Submit</button>
        </mat-dialog-actions>
    </form>
    </ng-template>

Component

openDialog() {
    let dialogRef = this.dialog.open(this.callAPIDialog);
    dialogRef.afterClosed().subscribe(result => {
        if (result !== undefined) {
            if (result !== 'no') {
              const enabled = "Y"
                console.log(result);
            } else if (result === 'no') {
               console.log('User clicked no.');
            }
        }
    })
}


onSend(form: NgForm){
  let data = form.value;
  console.log(data);
}

Answer №1

Check out the link below for more information: https://stackblitz.com/edit/ang-material-dialog-rxufmu

  1. You may want to review the format of your form inputs. Here is a helpful resource:

  2. Consider removing the matDialogClose property from the submit button and simplifying it. Make sure to validate the form data before closing the dialog.

  3. Instead of passing just the values, pass the entire form in ngSubmit so you can track its status and properties. Here's an example:

    (ngSubmit)="onSend(userForm)"
    

Answer №2

Here is a guide on retrieving form values and closing the MatDialog after form submission by making modifications to the app.component.ts file:

I declared the dialogRef variable at the class level, allowing you to access it in the onSend method to close the dialog.

import { Component,Input, TemplateRef, Injectable, ViewChild } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatFormFieldControl } from '@angular/material';
import { FormControl, NgForm, Validators,  FormBuilder, FormGroup  } from '@angular/forms';



@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [
    { provide: MatFormFieldControl, useExisting: AppComponent}   
  ]
})
export class AppComponent {
  @ViewChild('callAPIDialog') callAPIDialog: TemplateRef<any>; 
  @ViewChild('userForm') userForm: any;
  dialogRef: any;
  userModel: any = {};
  
  constructor(public dialog: MatDialog) {
  
   }

  openDialog() {

    this.dialogRef = this.dialog.open(this.callAPIDialog);
    this.dialogRef.afterClosed().subscribe(result => {
        console.log(this.userForm);
        if (result !== undefined) {
            if (result !== 'no') {
              const enabled = "Y"
                console.log(result);
            } else if (result === 'no') {
               console.log('User clicked no.');
            }
        }
    })
}


onSend(form: NgForm){
  let data = form.value;
  console.log('form submitted');
  console.log(this.userModel);
  this.dialogRef.close();
}

}
<div>
<button mat-raised-button (click)="openDialog()">Pick one</button>
</div>

  <ng-template #callAPIDialog>
        <form #userForm="ngForm" (ngSubmit)="onSend(userForm)">
        <h2 matDialogTitle>Add Organization</h2>
       
            <input   [(ngModel)]="userModel.organisationName" placeholder="Your organization" name="organisationName" [ngModelOptions]="{standalone: true}">
            <input matInput [(ngModel)]="userModel.enabled" [(value)]="Y" name="enabled" [ngModelOptions]="{standalone: true}">
          
        <mat-dialog-actions align="end">
            <button mat-button matDialogClose="no">Cancel</button>
            <!-- <button type="submit" mat-button matDialogClose="yes">Submit</button> -->
              <button type="submit" mat-button>Submit</button>
        </mat-dialog-actions>
    </form>
 
    </ng-template>

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

Having trouble accessing the 'value' property of undefined in Angular CLI

As a beginner in Angular, Angular CLI, Foundation, and Jquery, I am still learning and experiencing some challenges. Although I can retrieve information from my database, apply filters to display contacts of the same category, and show contact details with ...

The absence of definition for onSubmit is causing an issue in Angular 6

I am encountering an issue with validating the sign-in form as it is showing an error stating onSubmit is not defined. Below is the code snippet: import { Component, OnInit } from '@angular/core'; import { FormArray, FormControl, FormGroup, Vali ...

Show or hide a div based on the visibility of another div in Angular using *ngIf

Looking for a way to dynamically display images based on the visibility of another image? Consider the code snippet below: <div *ngFor="let badge of user.progress.unlockedBadges"> <img id="{{i}}_unlockedImage" *ngIf="badge == achievemen ...

Troubleshooting routing problems with Angular + Kubernetes + Nginx

In the current project I'm working on, I've been dealing with several routing issues which I believe stem from a configuration problem. I'm looking for anyone who has faced similar challenges to share their experiences. Project Overview: ...

Accessing Angular's Observable Objects

I am currently in the process of learning Angular and trying to work with Observables. However, I am facing an issue where I cannot extract data from an Observable when it is in object form. public rowData$!: Observable<any[]>; UpdateGrid() { this ...

What is the best way to declare a global TypeScript variable in a definition file to make it accessible for import?

My issue revolves around an external JS library that contains a global parameter: function Thing() { ... } ... var thing = new Thing(); I have a TypeScript definition file named thing.d.ts with the following content: declare var thing: ThingStatic; ex ...

The ngx-toaster message is showing a delay of about 30-40 seconds before displaying on the browser in Angular 11

Within the App.module file: Include ToastrModule in appModule ToastrModule.forRoot({ timeOut: 3000, preventDuplicates: true, }), Inside a specific component: this.toastr.error("test err"); The error message is taking quite a while to disp ...

Creating an async function in TypeScript to retrieve the coordinates of a particular location is a useful way to streamline the

I am looking to retrieve the coordinates of a location as the output of a function. The coordinates are already assigned within a fetch method, with latitudes stored as coordinates.lat and longitudes stored as coordinates.lng. [Currently, it is returning ...

An issue arose during resolution... Angular Library unable to resolve dependency

As I embark on creating my very first component library, things have been progressing smoothly. Now, I am at the stage where I am testing the library by incorporating it into new projects. The package.json file for my library project is set up as follows ...

Injecting multiple properties using @Inject MAT_DIALOG_DATA

Sharing this dialog across different cases requires receiving different data when a component uses it. Although I can successfully receive the first data, I am facing an issue where 'data2' is currently the same as 'data1'. Is there a ...

Is it possible to make two props mandatory only if one of them is utilized?

I am facing a challenge where I need to make two props required in a component if one of them is used. export type ComponentProps = { children: ReactNode height?: number width?: number } const Component: React.FC<ComponentProps> = ({ childre ...

What is the best method in typescript to combine objects in an array with identical properties but varying values?

interface IData{ cabinTo:string[]; cabinFrom:string; } const dataAfterIteration= [{cabinTo:"A",cabinFrom:"B"}, {cabinTo:"A",cabinFrom:"C"}, {cabinTo:"B",cabinFrom:"C"}, { ...

Styling with react-jss based on intricate conditionals

After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

Obtain the injector instance in Nest.js

How can I use Nest.js dependency injection service to create an instance of a dynamically loaded class? In Angular, I would typically use Injector.create. What is the equivalent method in Nest.js? ...

What could be causing the issue with my Angular integration with Jira Issue Collector to not function properly?

Looking to link the Jira issue collector with an Angular application I attempted something along the lines of Component.ts import { Component, OnInit } from '@angular/core'; import * as jQuery from 'jquery'; declare global { inter ...

Issue arises when using Ionic 7 tabs with standalone Angular components

Hey, I'm new to Ionic and trying to learn it. However, all the courses available are on the old versions 5 or 6. I attempted to learn it with Angular standalone but it didn't turn out as I expected. The new way of routing wasn't working for ...

Unable to locate a custom definition for TypeScript v3

When I am running my webpack dev server, Typescript is generating this error: ERROR in ./src/components/allowcated-resources/AllowcatedResources.tsx Module not found: Error: Can't resolve 'my-scheduler' in 'mypath\allowcated-resou ...

The movement of particles in tsparticles experiences interruptions when built in React, causing defects in their motion or noticeable stutter and lag

The performance is flawless in development mode with npm run start, but once deployed and running the production build (npm run build), there seems to be a disturbance in particle movement or a drastic decrease in speed. Despite experimenting with all ava ...

Encountering a 404 error with systemjs-angular-loader.js in a production environment

Currently, I am working on the most recent Angular/Quickstart project that utilizes systemjs-angular-loader.js to load app-relative HTML templates without the need for the moduleId property. During development and testing with "npm start" to serve pages, ...