Validating forms in Angular 6 upon submission

In my current scenario, I am faced with the need to validate fields only upon submission.

Due to the complexity of my form, which includes FormArrays and FormGroup, I have segmented it into multiple components such that each component represents a distinct group. Additionally, I have a universal component designed to simplify the creation of Input elements along with validation messages.

Unfortunately, Angular's default behavior is to validate forms as soon as any input is typed, and there is no built-in option to delay validation until after submission.

Answer №1

Unique Solution #ABC

One effective approach is to introduce a boolean property in the parent component, such as submitted = false, which can be manually set to true upon form submission by the user. This property can then be passed down through multiple layers of components using @Input() bindings until it reaches the general input component. In this component, the property can be used in conjunction with ngIf to display any errors.


Innovative Solution #XYZ

After closely examining Material Angular inputs and their custom validation matchers, I delved into the source code and discovered that the base classes, NgForm and FormGroupDirective, are injected into constructors. Through dependency injection, it became apparent that one could access the submitted property by obtaining the FormGroupDirective/NgForm instances. By utilizing dependency injection, the submitted property can be exclusively housed within the general input component. Here's an example snippet showcasing how this can be achieved:

constructor(
  @Optional() private form: NgForm,
  @Optional() private group: FormGroupDirective,
) { }

ngOnInit() {
  this.group.ngSubmit.subscribe(e => {
    this.submittd = this.group.submitted || this.form.submitted;
  });
}

To visualize this concept in action, a demonstration has been created. Upon accessing the provided StackBlitz link, you can observe firsthand how the property tracking functions.

Initiate the process by checking the initial state of the FormGroupDirective in the console. Subsequently, trigger the ngSubmit event by clicking the submit button. The Funny button displays the updated submitted status present on the FormGroupDirective instance.

An additional example incorporates error messaging alongside color indicators for input fields. Feel free to explore this functionality in action by visiting the following StackBlitz link. Simply delete the input value and click "Submit" to witness the dynamics in play.

Answer №2

Check out this post for details on how to optimize performance:

this.login = new FormGroup({
   email: new FormControl(),
   password: new FormControl()
}, { updateOn: 'submit' });

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

Guide on Implementing Class on Dropdown in AngularFollow these steps to effectively utilize the

Currently, I am facing an issue with my Angular project. I am trying to implement a Directive that activates a dropdown menu. However, the 'open' class is deprecated in Bootstrap 3, and I am using Bootstrap 5. How can I transition to the 'sh ...

What is the proper procedure for sending an array to the server?

Whenever I attempt to send an array in a request, the result returns as null. Request Payload Result: [ {nom_name: "Test", cost: 500, quantity: 1, parentOrder_id: 19}, {nom_name: "35634", cost: 100, quantity: 1, parentOrder_id: ...

Creating XML templates in Angular 7: A comprehensive guide

How do I pass XML values in Angular 7 when the API requires this specific format of XML code? -modifydata "<datasets><dataset select=\""always\""> <replace match=\""Letter/@FName\"" value=\""Nazeeeeeeeeeeeeer\" ...

Tips on ending an interval in rxjs once it has started

Implemented a code in an Angular component to retrieve data from a service every 10 seconds on initialization. Now, I need to find a way to stop the interval after a certain period of time such as 5 minutes or when all the necessary data has been collected ...

Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code: // RxJS v6+ import { lastValueFrom, Subject } from 'rxjs'; import { scan } from 'rxjs/operators'; async function main() { const subject = new Subje ...

Accessing Route Data in Angular's AppComponent

In my app-routing.module.ts file, I have set up the following routes: const routes: Routes = [ { path: 'abc/:id', component: AbcComponent, data: { category: 'Public' } }, { path: 'xyz/:id/tester/:mapId', componen ...

Angular2 route-driven themes

Exploring Different Themes for Two Routes: /books and /paintings Seeking a Solution to Include Specific Stylesheet Links in index.html For the /books route, I wish to include: <link rel="stylesheet" href="/assets/css/reading-theme.css" /> And for ...

What is the best way to send parameters from an Angular application to a Node.js API?

How can I correctly pass the id from Angular to my "/rating" HTTP endpoint? This is the method I am currently using: apiUpdateRating(id){ return this.http.get('http://localhost:8080/rating', { params:id }); } When ...

What is the best way to bypass using an if/else statement in TypeScript when dealing with mocha and returning undefined values

A unique spline able to be intertwined and produce a new version of itself, most of the time. export default class UniqueSpline { public intertwinedCount: number; constructor(parent?: UniqueSpline) { this.intertwinedCount = parent && pare ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Angular: Animate newly updated items in a constantly evolving and refreshed list

I'm facing a challenge with my template that includes a simple list with animated items (:enter & :leave animations). @itemAnimation *ngFor="let item of list; There's also an "ADD" button that triggers a modal dialog for users to add new it ...

Ways to trigger a Node.js logout API upon closing the browser tab

Having difficulty with authentication during login and logout: The logic I need to implement is when a user closes the web browser, I want the client to notify the server that the customer has logged out. I am using Angular and Node for the application. ...

ng2-dragula error: issues with setting options and dropping version

It seems that version 1.5.0 supports this.dragulaService.setOptions, while version 2.1.1 does not, and vice versa with this.dragulaService.drop subscribe where version 2.1.1 supports it but 1.5.0 does not. Check out the Stackblitz Fork for version 1.5.0 ...

What are the benefits of incorporating component A into component B as a regular practice?

I am considering creating an instance of Component A within Component B, but I'm unsure if this is a best practice in Angular or if it will just cause confusion. Component A: This component generates a modal window asking the user to confirm file de ...

The parent component can successfully call the setState function, but for some reason, the

In my code structure, I have the following setup (simplified): Here is the parent component: //code... const {handleClick} = useClick; <ul> {actions.map((action: string) => ( <li onClick={() => handleClick()} key={uuidv4()}> ...

What is the best way to prevent the hassle of manually reloading a VS Code extension each time I make updates

While working on my VS Code extension, I keep encountering the issue of opening a new instance of VS Code every time I run the extension to view recent changes. This becomes especially tedious when using VS Code remote and having to enter my password twice ...

What is the best way to pass a string array in a post request using HttpClient in Angular 14?

Trying to send a string array using HttpClient's post method to my backend. getAnnouncementsByIds(ids: string[]): Observable<Announcement[]> { return this.http.post<Announcement[]>(`${environment.serverUrl}${this.urlGetAnnouncementsByIds ...

Angular 6 - The requested resource does not have the necessary 'Access-Control-Allow-Origin' header

I am currently working on an Angular 6 project that includes a service pointing to server.js. Angular is running on port: 4200 and Server.js is running on port: 3000. However, when I try to access the service at http://localhost:3000/api/posts (the locat ...

Angular 5 - Implementing Horizontal Scroll with Clickable Arrows

In my Angular application, I have successfully implemented horizontal scrolling of cards. Now, I am looking to enhance the user experience by adding "Left" and "Right" buttons that allow users to scroll in either direction within their specific msgCardDeck ...

Troubleshooting the malfunction of the Angular 2 Tour of Heroes project following the separation of the app

Recently, I encountered a challenge while following a tutorial on learning Angular 2. Everything was going smoothly until I reached the point where I had to divide appcomponent into heroescomponent & appcomponent. Is there anyone else who has faced th ...