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

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Type narrowing is ineffective for discriminated unions in most cases

Consider the type definition provided below: type A = { a: string } | { a?: undefined; b: string } This essentially means that if you include a, it should be the only property provided. If you do not include or have a as undefined, then you also need to p ...

Conditional formatting for form field styles

Is there a way in Angular to conditionally render a material style? For instance, I am looking to apply the following style only to my Password form field text, and only when both input boxes have content: .mat-form-field-appearance-outline .mat-form-fiel ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Webpack focuses solely on serving HTML files, neglecting to deliver the underlying code

Hey there! I'm currently working on a project that involves using React, TypeScript, and Webpack. I ran into some errors previously that prevented the code from compiling, but now that's fixed. However, when I run webpack, it only serves the HTML ...

What is the procedure for a parent component to transmit HTML to a child component within Angular?

How can a parent component pass multiple ng-templates to a child component? For example, the parent component includes multiple ng-templates: <app-childcomponent> <ng-template>Item A</ng-template> <ng-template>Item B</n ...

Issue with auto formatting quotes in IntelliJ / WebStorm is no longer functioning as expected

Currently, my TSLint configuration is set to permit the use of single quotes (') instead of double ones ("). Previously, I was able to conveniently switch all instances of " to ' in a file by using the Reformat Code shortcut CTRL + ALT ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

The attribute 'date' is not found within the class 'EmployeeScheduleExceptionModel', however, it is present in the parent class from which it inherits

I am working on a TypeScript project and I have defined my configurations in the tsconfig.json file as shown below: { "include": ["src*"], "compilerOptions": { "target": "es2021", &q ...

What is the best way to exhibit information from a lone table column in a modal using Angular 7?

Is there a way to have an "edit" button beside each row in the appointments table that triggers a modal popup allowing users to change appointment dates? Unfortunately, I'm facing an issue where the modal does not pop up and my screen turns white. ** ...

Why is it that I am not receiving JSON data in my Angular application?

I am currently working on a class within a webapi public class ResponseObject { public int Success { get; set; } public string Message { get; set; } public object Data { get; set; } } Within my ASP.NetCore, I have the following method: publi ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

Learn the process of implementing an SVG icon in your Angular Material project

I'm currently attempting to incorporate a single icon into my Angular Material application. Following the documentation, I have implemented $mdIconProvider in the following manner: app.config(function($stateProvider, $urlRouterProvider, $mdIconProvid ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

Phaser3 encountering issues while loading files from Multiatlas

Attempting to utilize the multiatlas functionality in Phaser alongside TexturePacker. Encountering this issue: VM32201:1 GET http://localhost:8080/bg-sd.json 404 (Not Found) Texture.js:250 Texture.frame missing: 1/1.png The JSON file can actually be fou ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...