What are the steps to manually activate input validation in Angular 2?

Having two inputs is the scenario here:

  • The first input undergoes custom validator application
  • The second input has a dynamic and editable value utilized in the custom validator

If the custom validator is applied on the first input, then focus shifts to the second one for a value change - triggering re-validation for the first input is what's desired...

Currently, the first input only re-validates upon changing the value... Any ideas for improvement?

Upon focusing on the first input, its reference can be accessed:

<input
    name="mEnd"
    class="form-control"
    [(ngModel)]="endDate"
       ...
    #endDateInput="ngModel"
    (focus)="clog(endDateInput)"
>

Is it possible to trigger re-validation using the formControl reference methods of the input?

Answer №1

To ensure accuracy, you have the option to update the validation status of a formControl

form.controls['myControl'].updateValueAndValidity();

Answer №2

After trying it out, I discovered that this approach is significantly more effective.

this.myForm.markAllAsTouched();

Answer №3

To work with a template-driven form, you can utilize the ViewChild decorator to access the form:

@ViewChild('myForm') public form: NgForm;

After that, you can validate either a single field or the entire form group by utilizing the method mentioned below:

this.form.controls.myControl.updateValueAndValidity();

Answer №4

None of the solutions provided for Angular 12 worked for me, so I took a different approach by adding a hidden button to the form.

<button type="submit" [style.visibility]="'hidden'" #submitBtn>Submit</button>

In the controller, I used ViewChild to reference this hidden button.

@ViewChild('submitBtn') private buttonSubmit:ElementRef;

Then, I programmatically triggered a click on the desired event.

 submitFormByKey(){
    this.buttonSubmit.nativeElement.click();
}

By doing this, I was able to simulate a submit action and trigger validation for all fields in the form.

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

Retrieving values from multiple inputs in NightwatchJS

Can nightwatchjs be used to retrieve values from multiple inputs simultaneously? I am looking to verify the values of several input fields at once. Your help is much appreciated. ...

Node.js is great at hosting HTML files, but struggles when it comes to loading script files within those pages

Recently, I’ve been working on creating a simple login page using a mongoDB database along with Node.js and express. Since I'm still new to Node.js, I'm facing an issue that seems more complicated than it actually is. The main problem I’m en ...

"ReactJS error: Unable to upload file due to a 400

Every time I attempt to upload a file, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 404". I'm puzzled as to why this is happening. Here's the section of my code that seems to be causing the issue. ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

What is the procedure for adding a background to a primeNg Tree component?

Working with Angular CLI 6 and primeNg version 6.0.1 I have been attempting to customize the background of the tree component without success. When I try using style="background:red" in the HTML file, the tree display becomes distorted with a height of on ...

Accessing the value returned by an asynchronous function in Node.js with Electron

As I embark on a new project, my goal is to take user input, process it through a function, and then return the updated value back to the user. Despite being a novice with async functions, I've done extensive research but still can't pinpoint if ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Error in TypeScript: It is not possible to use a component with MUI styling as a JSX element

I can't figure out what's going wrong. I'm attempting to include a child component in the main page, and I have a feeling it has something to do with MUI styles being applied at the end. I removed all unnecessary code and still encounter thi ...

Using Jquery to Retrieve the Content of Head and Body Tags from a String

Here is a string that I currently have: <head> This is the Head </head> <body> <div> <div> <p> Body Content <br /></p> <p>&nbsp; Hello World <br />< ...

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

Example of material-ui-pickers: Error - Object(...) is not a function

Trying to implement a basic material UI pickers example using a clean project and following the installation and usage instructions provided here: An error message is displayed as follows: TypeError: Object(...) is not a function Module../node_modules/@m ...

Cease the continuous scrolling of the display element now

I'm having trouble with my progressbar animation when scrolling. It seems to run multiple times instead of just once. I apologize if there's an error in my code. Could someone please assist me? This is the code I am using: <div class="demo- ...

Having issues with an Angular reactive form that includes a custom form-level validator and the 'blur' updateOn option?

Having issues combining the following: angular reactive form custom validator at form level (cross-field validator) usage of the 'updateOn' option set to 'blur' A demonstration of the problem can be found in this simple stackblitz: h ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

Is it possible to use JavaScript to make a CSS animation mimic the behavior of a :hover effect?

My CSS animation looks like this: HTML: <div class="container" id="cont"> <div class="box show"></div> </div> CSS: .container { width: 100vw; height: 100vh; } .box { position: absolute ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...

Unlocking the Potential of Checkbox Values in AngularJS

I am attempting to extract data from a $rootScope object that has been linked to the checkboxes. HTML: <tr ng-repeat="system_history in SystemHistoryResponse.system_history"> <td><input type="checkbox" ng-model="versionValues[system_histor ...

"Sorry, but it appears that the tooltip-basic module is

I have been attempting to implement ng-bootstrap tooltips (or any of their widgets) in my Angular 7 application. Despite what seems to be a successful installation of ng-bootstrap, I am facing an issue where nothing happens when I try to use the tooltip as ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

In C#, transforming JSON serialization to replace single backslashes with double backslashes

When generating JSON to be included directly in an HTML file, it's important to wrap the JSON in a JavaScript string. For example: var dataContacts = '{"Contacts":[{"Id":0,"Active":false,"Company":"Rory The Architect\\, Melt"} ...