The submission functionality of an Angular form can be triggered by a separate button

I am currently developing a Material App using Angular 12.

The Form structure I have implemented is as follows:

<form [formGroup]="form" class="normal-form" (ngSubmit)="onSubmit()">
  <mat-grid-list cols="2" rowHeight="300px">
    <mat-grid-tile>
      <div class="controles-container">
        <input type="hidden" formControlName="Id">
          <mat-label><strong>Active</strong></mat-label>
              <mat-slide-toggle formControlName="IsActive"
                  [checked]="checked">
              </mat-slide-toggle>
              <textarea matInput hidden></textarea>

        <mat-form-field>
          <input formControlName="Name" matInput  placeholder=" Notification Name" >
          <mat-error>This field is mandatory</mat-error>
        </mat-form-field>
        <mat-form-field>
          <mat-select formControlName="ProcessorName" placeholder="Processor Name">
            <ng-container *ngFor="let processors of dataSourceProcessors">
              <mat-option value="{{processors.Value}}">{{processors.Text}}</mat-option>
            </ng-container>
          </mat-select>
        </mat-form-field>
      </div>
    </mat-grid-tile>
    <mat-grid-tile>
      <div class="controles-container">
          <mat-label><strong>Channel</strong></mat-label>
          <li *ngFor="let chanel of dataSourceChannelLevel">
            <mat-checkbox id={{chanel.NotificationLogLevel.Id}} formControlName="Channel" (change)="onChangeEventFunc( $event)">
              {{chanel.NotificationLogLevel.Name}}
            </mat-checkbox>
          </li>
        <div class="button-row">
          <button mat-raised-button color="warn" (click)="onClose()">Close</button>
          <button mat-raised-button color="primary" type="submit" [disabled]="form.invalid">Create</button>
        </div>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</form>

In the component, I have initialized the following Form controls:

 form:FormGroup=new FormGroup({
    Id: new FormControl(null),
    Name: new FormControl('',Validators.required),
    IsActive: new FormControl(true),
    ProcessorName: new FormControl(0),
    Channel: new FormControl(''),
  });

There are two buttons in the Form - 'Create' which triggers Form Submit, and 'Close' button...

The issue I am facing is that when I click on the Close button, both onClose() and onSubmit() functions are getting called simultaneously.

Can anyone help me identify what I might be missing?

Thank you!

Answer №1

In the event that the button serves as a submit button and is located within or associated with a form, but does not possess the attribute type="button", it is advisable to include type="button" to prevent inadvertently triggering the onsubmit function of the form element.

<button id="btn-close" class="btn btn-danger" (click)="closeModal()" type="button">Close</button>

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

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

Bringing in AuthError with TypeScript from Firebase

Is it possible to verify if an error is of type "AuthError" in TypeScript when using Firebase? I have a Https Callable function with a try/catch block that looks like this: try { await admin.auth().getUser(data.uid); // will throw error if user doesn& ...

Error encountered during Jasmine unit testing for the ng-redux @select directive

Here is a snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { select } from 'ng2-redux'; import { Observable } from 'rxjs/Observable'; import { PersonalDetailsComponent } from ' ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

Visual Studio 2015 does not support compiling typescript files

I'm encountering some difficulties while attempting to set up node with typescript support in Visual Studio 2015 for my web API application. To start fresh, I deleted the node_module folder along with the package.json and tsconfig.json files. Followi ...

Navigating through the key type within a mapped structure

I am working with a mapped type in the following structure: type Mapped = { [Key in string]: Key }; My understanding is that this setup should only allow types where the key matches the value. However, I have found that both of the cases below are permitt ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

How can I inform Typescript that an interface will exclusively consist of defined members?

My interface looks like this interface Person { name?:string; age? :number; gender?:string } I need to reuse the same interface type, but with a modification indicating that all members will never be undefined. The updated version would look like this: ...

Unable to properly display date formatting in AG-Grid using the Angular date pipe

Currently, I am utilizing ag-grid in conjunction with Angular 8. Within my table, there is a column where my intention is to exhibit dates in a concise format. In order to achieve this, I opted to utilize the Angular date pipe. However, it appears that the ...

Tips for configuring the Index column within an Angular Mat-table (when the dataIndex displays 'NaN')

My Mat-Table is working perfectly, but I am looking for a way to add an auto-increment index. Below is the HTML code: <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="no"> ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

How to inject a regular class in Angular2 without the @Injectable decorator

angular: 2.0.0-beta.9 Can we inject a non-@Injectable class into a component? For instance, if this class originates from an external Third party library. ...

Tips for changing a function signature from an external TypeScript library

Is it possible to replace the function signature of an external package with custom types? Imagine using an external package called translationpackage and wanting to utilize its translate function. The original function signature from the package is: // ...

Choosing Vue select options depending on a condition

I am working on a dropdown template with Vue.js and have encountered some challenges. Here is the basic structure of my dropdown: <select v-model="selectedClient" class="stat-select text-u-c"> <option disabled value="">Please select a Client ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

I seem to be failing at properly executing Promises... What crucial element am I overlooking in this process?

Within my project, there exists a file named token.ts which contains a function that exports functionality: import * as jwt from 'jsonwebtoken'; import { db, dbUserLevel } from '../util/db'; export function genToken(username, passwor ...

Unexpected behavior noticed with Angular Material 2 Reactive Forms: the mat-error directive does not display when validating for minLength. However, it functions correctly for email and required

Try out this Stackblitz example: https://stackblitz.com/angular/nvpdgegebrol This particular example is a modified version of the official Angular Material sample, where the validation logic has been altered to display the mat error for minLength validati ...