Prevent submission of Angular form while still displaying errors upon clicking

My goal is to implement a form using Angular, where the submit button remains disabled until the form is valid. When the user clicks the button, the background color of any invalid input should change along with displaying an alert message below the form.

I have attempted to manually disable the button in TypeScript and change the background color based on validity, but this causes the color to change immediately as the form is initially invalid. The desired behavior is for the background color to only change after the submit button has been clicked.

The form should prevent submission of any data until all required input fields are valid while visually indicating which inputs are invalid through background color changes. Below is the HTML code for the form:

<form class="w-50 mb-5 mt-5" (ngSubmit)="onSubmit(f)" #f="ngForm">
      <!-- Form inputs here -->
    </form>

Below is the corresponding TypeScript code snippet:

@Input() selectedDiv: number;
  selectedPackage: string;

  <!-- Methods for handling form data and package selection -->

  constructor() { }

  ngOnInit() {
    // Initialize package information based on the selected division
    this.changePackageInfo();
  }

Answer №1

To maintain the state of a form, consider using a Boolean variable. Update this variable only upon form submission and utilize it in the template to control error visibility.

Inside Component :

onSubmit(form: NgForm) {
    this.showError = form.invalid;
    if(form.invalid) return;
    // Add your submission logic here.
}

Usage in Template:

<div>
    <label for="email">
        <span style="color:red;font-weight:bold;">*</span>
        Email
    </label>
    <input 
        id="email" name="email" [(ngModel)]="emailText" 
        required #email="ngModel"
        [ngStyle]="{'background-color':showError && email.invalid ? 'red': ''}">
</div>

For a live example of the code in action, check here

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

"Enhance your project with the power of Angular CLI, npm,

I am working on an Angular 2 project built with npm and angular-cli. I want to be able to copy a folder into another folder before every compilation. The goal is to have multiple themes in individual folders, and then select one of those themes using a va ...

Printing with Angular 7: A Handy Service

As I was attempting to generate the angular form, I came across this example on https://stackblitz.com/github/IdanCo/angular-print-service?file=src%2Fapp%2Fapp.component.html I explored the named routes but faced some confusion. There were two points tha ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Expo background fetch initialized but not activated

During the development of my React Native app, I encountered the need to perform periodic background fetches from another server. To achieve this, I utilized two classes from Expo: import * as BackgroundFetch from 'expo-background-fetch'; import ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

Utilize a combination of generic parameters as the keys for objects in TypeScript

Is there a method to utilize multiple generic parameters as object keys in TypeScript? I came across this answer which works well when there is only one parameter, but encounters issues with more than one. The error message "A mapped type may not declar ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

Dealing with the 'UNIFIED_TEST_PLATFORM' issue while trying to compile an Ionic android app that utilizes tesseract.js and capacitor core

I recently set up an Ionic Angular project and integrated Capacitor to access native code functionalities. My project utilizes tesseract.js, as well as Capacitor core and camera plugins. However, I encountered an error while building the Android project: ...

Is the transcluded content visible to the class as a whole?

Angular2 makes it simple to create a component like this: @Component({ selector: 'some', properties: ['header'] }) @View({ template: ` <div> <h2>{{ getFormattedHeader() }}</h2> <p><conte ...

What methods does TypeScript use to verify primitive types during runtime?

Is it true that Typescript removes any type or interface at compile time? If so, how is it possible to determine an object's primitive type using the typeof keyword? Are custom interfaces handled differently than primitive types? const a = "strin ...

The error message "core.js:10101 NG0303: Unable to link to 'matCellDefOf' because it is not a recognized property of 'td'" was displayed on the console

While utilizing Mat table from Angular Material, an error appears in the console as shown in this image: core.js:10101 NG0303: Can't bind to 'matCellDefOf' since it isn't a known property of 'td'. View image description here ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

Can anyone help me understand the meaning of this unfamiliar icon in WebStorm's autocomplete feature

When the autocompletion feature is performing type inference, you will see this icon: https://i.sstatic.net/zOZcC.png ...

What is the procedure for including a js file in typescript?

I am trying to import a js file in typescript and access objects and functions within the file. I have added the js file in index.html, but it is not working as expected. I tried using "import '[js file path]'" but it did not work. import { Comp ...

Generate code in Yii2 using the active form

This is the code I am using in Yii2: <?= $form->field($model, 'username')->label(false); ?> <?= $form->field($model, 'password')->label(false); ?> It produces the following output: <div class="form-group fi ...

delete entry from PrimeNG data grid

I have been encountering an issue while trying to delete an item from a binding list: <p-dataTable [value]="items"> <p-column styleClass="col-button"> <template let-item="rowData" pTemplate="body"> <button type="butt ...

Firemonkey: Accessing the parent form for a control

I am currently working on a custom control that requires access to the height of the main form it is placed on. The control is often nested within multiple panels, so I have developed the following code to help me reach the main form: TControl * control = ...

I possess both a minimum and maximum number; how can I effectively create an array containing n random numbers within

Given a minimum number of 10.5 and a maximum number of 29.75, the task is to generate an array within these two ranges with a specific length denoted by 'n'. While the function for generating the array is provided below, it is important to calcul ...