Click function for Angular bootstrap button

I have implemented a basic form in my template that already has validation. My main issue is how to check when the user clicks on the button after filling out all required fields?

<section class="contact-area pb-80" style="margin-top:10%">
    <div class="container">
        <div class="section-title">
            <h2>Your Information</h2>
            <div class="bar"></div>
            <p>Please provide accurate information so we can contact you accordingly.</p>
        </div>

        <div class="row h-100 justify-content-center align-items-center">
            <div class="col-lg-6 col-md-12">
                <img src="assets/img/1.png" alt="image">
            </div>

            <div class="col-lg-6 col-md-12">
                <form id="contactForm">
                    <div class="row">
                        <div class="col-lg-12 col-md-12">
                            <div class="form-group">
                                <input type="text" name="name" id="name" class="form-control" required placeholder="Enter your name">
                            </div>
                        </div>

                        <div class="col-lg-12 col-md-12">
                            <div class="form-group">
                                <input type="email" name="email" id="email" class="form-control" required placeholder="Enter your email">
                            </div>
                        </div>

                        <div class="col-lg-12 col-md-6">
                            <div class="form-group">
                                <input type="text" name="phone_number" id="phone_number" required class="form-control" placeholder="Enter your number (Whats app)">
                            </div>
                        </div>

                        <div class="col-lg-12 col-md-6">
                            <div class="form-group">
                                <input type="text" name="msg_subject" id="msg_subject" class="form-control" required placeholder="Enter your skype name">
                            </div>
                        </div>


                        <div class="col-lg-12 col-md-12">
                            <button type="submit" class="btn btn-primary">Send Message</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>

My challenge lies in determining how to trigger the function I created, submit(), only when all form fields are filled before the user clicks on the Send Message button.

The current approach I've attempted involved adding (click)="submit()" to the button. However, this causes the function to be called every time the button is clicked. I specifically need it to execute only when all required fields are completed.

Answer ā„–1

Template Example:

<form #myForm="ngForm">
  <input ngModel name="username" type="text" required />
  <input ngModel name="user-email" type="email" required />
  <input ngModel name="user-phone" type="text" required />

  <button (click)="submitForm(myForm)">Submit</button>
</form>

Component Logic:

submitForm(form: NgForm) {
  console.log(form.invalid);
}

Remember to import FormsModule in your module:

import { FormsModule } from '@angular/forms';

@NgModule({
  // ...
  imports: [..., FormsModule, ...],
  // ...
})

Answer ā„–2

Ensure to include the following code in your app-module by importing { FormsModule } from '@angular/forms' and adding it to the imports array.

@NgModule({
  imports: [FormsModule],
})

In your form element, create a template variable called myForm, and on the button tag, utilize property binding like [disabled]="!myForm.form.valid". This will only enable the Submit button when all form elements are filled out correctly.

Template file:

<form #myForm="ngForm" method="POST" (ngSubmit)="submitForm(myForm)">
  <div>
    <label>Name</label>        
    <input name="name" type="text" required ngModel/>
  </div>
  <div>
    <label>Email</label>
    <input name="email" type="email" required ngModel/>
  </div>
  <div>
    <label>Phone no</label>
    <input name="phone" type="number" required ngModel/>
  </div>

  <button type="submit" [disabled]="!myForm.form.valid">Submit</button>
  <pre>{{myForm.value | json}}</pre>
</form>

You can check out my code snippet on StackBlitz

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

To run multiple environments with react-native-dotenv in a React Native project using Typescript, only the local environment is activated

Currently, I am facing an issue while trying to initialize my React Native app with TypeScript in three different environments - development, local, and testing. When I attempt to run APP_ENV=testing expo start or APP_ENV=development expo start, it always ...

Oops! Property 'month' cannot be set on undefined value due to a TypeError

Despite not receiving any errors from Visual Studio Code, Iā€™m encountering an error in Chrome's console. Below is the code snippet from my interfaces.ts file: export interface Data1{ month: string; employeeName: string; date: string; employmentSta ...

Inserting a pause between a trio of separate phrases

I am dealing with three string variables that are stacked on top of each other without any spacing. Is there a way to add something similar to a tag in the ts file instead of the template? Alternatively, can I input multiple values into my angular compo ...

Angular 2 does not allow access to the getSize() properties while using Protractor

I have been utilizing the Angular2 Go Protractor setup in an attempt to conduct end-to-end tests on Angular 2. While attempting to retrieve the size of an element, I have encountered issues with the properties not being accessible. For instance: var myEl ...

Angular 6 - accepting an HTTP GET request as the app loads

Upon the initial startup of my Angular application, just before its pages are loaded onto the user's browser, I aim to retrieve certain information from the HTTP request that triggered the app's launch. More precisely, I am looking to obtain the ...

What are the steps to display 10 items sequentially with the angular2-infinite-scroll package?

I'm currently working with the angular 2 infinite scroll module and I need to display 10 elements at a time. When the user scrolls down, the next 10 elements should be shown and the scrollbar should adjust accordingly. I've tried several methods ...

Obtain the targeted tab name in Angular

I am working with a piece of html code that displays different pills, and I am trying to find a way to get the name of the selected one using Angular: <ul class="nav nav-pills mb-5 justify-content-center" id="pills-tab" role="tablist"> <li clas ...

The package '@angular/core' is not listed as a dependency when upgrading from Angular 8 to Angular 9

Encountering an error while trying to update from Angular 8 to Angular 9. āœ” Successfully installed package. Using npm as package manager. Checking for installed dependencies... No dependencies found. '@angular/core' package is not recognized as ...

What is the best way to verify a function that produces multiple outcomes?

I have a scenario where an effect returns first action A and then action B @Effect() myCustomEffect$: Observable <Action> = this.actions$ .ofType('CUSTOM_ACTION') .switchMap(() => Observable.of( // notifying subscribers about a ...

What is causing this error? The length of this line is 118 characters, which exceeds the maximum allowed limit of 80 characters for max-len

I am encountering issues while attempting to upload my function to Firebase, specifically receiving two errors as follows: 39:1 error This line has a length of 123. Maximum allowed is 80 max-len 39:111 warning 'context' is defined but ...

Managing the dispatch of a successful action in a component

In my component, I have a form that adds items to a list. Once an item is successfully added, I want to reset the form using form.resetForm();. However, I am struggling to determine when the action of adding the item has been successful. I attempted to sub ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...

Navigating an angular collection like a pro

I have the following example data structure within a Component: const Questions = { "java": [ {text: "Is this a question?", answer: "Yes"}, {text: "Another question", answer: "Yes"} ], "python": [ {text: "A different qu ...

Creating visual content using Webpack and Angular2

I have a small Angular2 app that utilizes Webpack for project building and scaffolding. One issue I've encountered is the inability to load images specified in TypeScript files during production. After running npm run build, I noticed that these imag ...

VSCode Troubleshooting: When TypeScript Doesn't Recognize Installed Libraries

Lately, I've encountered a problem when using TypeScript in VSCode. Whenever I install a new library through npm, TypeScript doesn't seem to acknowledge the library right away. For instance, after adding the query-string library and attempting to ...

Close several dropdowns at once with ng-bootstrap

Within my Angular app, there are two dropdowns that I have integrated: <div class="input-group"> <input id="startDate" type="text" class="form-control" aria-label="Start date" ...

Leverage rxjs/Typescript to transform an array nested within the data received from an external API

Exploring Typescript/Javascript is a new adventure for me, especially as I delve into the world of rxjs. Here's a snippet of code that I've been working with: return this.http.get<IXenoCantoResponse>(`${this.corsAnywhereUrl}${this.xenoCant ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Is there a way to mock a "find" call in mockingoose without getting back "undefined"?

I am currently working with mockingoose 2.13.2 and mongoose 5.12.2, leveraging Typescript and jest for testing purposes. Within my test scenario, I am attempting to mock a call to my schema's find method. Here is what I have tried: import mockingoose ...

What is the most effective method to inform TypeScript that every element in an array is present in a Map?

Consider a scenario where you are creating a Map from an array of objects with unique ids as keys, and then accessing the map from another array that shares the same ids: const arr1 = [ {id: 'a', firstName: 'Mike'}, {id: 'b&apo ...