Dismiss the validator upon completion of submission

Two textboxes were created, one for the title and another for the name.

Validations have been implemented to only submit information if both textboxes are filled.

The issue arises when attempting to clear the variable values after submission, triggering validation messages.

Is there a way to submit successfully and clear variable values without triggering the validator?

DEMO

html

<div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="title..." [showClearButton]="true" [(ngModel)]="title">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Title">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>
<div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="name..." [showClearButton]="true" [(ngModel)]="name">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Name">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>

<dx-button text="Submit" [useSubmitBehavior]="true" (onClick)="Save()"></dx-button>

.ts

title: string;
name: string;

Save(){
  if(this.title == "" || this.title == undefined || this.name == "" || this.name == undefined){
  }
  else{
    alert("Sucess !!");
    this.title = "";
    this.name = "";
  }
}

Problem

https://i.sstatic.net/cRXpb.png

After successful submission and clearing variable values, the validator is unexpectedly triggered, disrupting the expected initial state.

Answer №1

One handy trick I often use is to clear all validators after submitting a form.

  @ViewChildren(DxValidatorComponent) validatorViewChildren: QueryList<DxValidatorComponent>;

  private clearDxValidators = () => {
    this.validatorViewChildren.toArray().map(ref => {
      ref.instance.reset();
    })
  }


To learn more, check out the reset() method documentation

Answer №2

One workaround you can try is by wrapping the template in a form and then checking if it's pristine to determine whether to display the validator message or not. Instead of setting your properties to an empty string, resetting the form after importing it into the component through ViewChild() could be a solution.

Although this may feel like a hack, ideally the toolkit you're using should handle this automatically. If it doesn't, it might be worth considering why you are using it in the first place.

It is also recommended to explore Angular Reactive Forms for further insights.

I have included my suggested changes in a Stackblitz.

Best of luck with your project!

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

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

What is the process for retrieving the serial number of a hardware device in Ionic 2?

I recently encountered an issue while trying to retrieve device details. I was able to fetch the UUID of the hardware device, but unfortunately, the serial number was inaccessible. Any suggestions or insights on how to obtain the serial number would be g ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

Structuring your Angular 6 application and server project

What is the recommended project structure when developing an Angular 6 application and an API server that need to share type definitions? For example: On the client side: this.httpService.get<Hero[]>(apiUrl + '/heroes') On the server si ...

Switching Angular fxLayout from row to column based on a conditional statementHere is an explanation of how to

Visit this link for more information Is there a way to set direction based on a specific value? <div if(value) fxLayout='row' else fxLayout='column'> ...

ng-bootstrap component 404 error on final angular2 release

angular2 final release. ng-bootstrap alpha v.5 bootstrap components are functioning on html, however when attempting to import them like this import {ViewChild} from "@angular/core/src/metadata/di"; import {NgbDropdown} from "@ng-bootstrap/ng-bootstrap/d ...

Encountering issues with the command npm install --save web-animations-js, the

Issue encountered while trying to run "npm install --save web-animations-js". It seems like the request to https://registry.npmjs.org/web-animations-js failed due to a mismatch in the Hostname/IP in the certificate. The error message indicates that the Hos ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

How to delay setting a property in Angular 2 until the previous setter has finished execution

Hey there, I'm facing an issue with my component. Within my component, I have an input setter set up like this: @Input() set editStatus(status: boolean) { this.savedEditStatus = status; if (this.savedEditStatus === true && this.getTrigg === t ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...

What steps can be taken to skip the email verification in Auth0 when updating a password by confirming the old password?

I am in need of creating a personalized page for changing passwords using auth0. I want the process to involve directly modifying the password without requiring an email with a password change link. Additionally, it needs to have a feature for confirming t ...

A guide on incorporating a single class object of type Observable<any> into HTML

I'm currently working with Angular4 and have a Windows Timer subscribed observable in my typescript file. this.dynamicTime = new Observable<string>((observer: Subscriber<string>) => { setInterval(() => observer.next(this ...

The Angular API request is continuously retrieving data every single second

I recently inherited some Angular/ng-bootstrap code that included a table with static data, which was functioning perfectly. However, the requirement now is to fetch the data from an API call. In an attempt to modify it accordingly, I referred to an answer ...

Set the component variable to hold the output of an asynchronous method within a service

As I work on developing an application, I aim to keep my component code concise and devoid of unnecessary clutter. To achieve this, I plan to offload complex logic into a service which will then be injected into the component. Suppose my component includes ...

What could be causing my Angular Ngrx app's state not to render properly on the application?

Is there a way to automatically render the state when the app loads without having to click a button? I am currently facing an issue where the state is empty until I manually trigger the click function by pressing a button. I have tried using this.store.se ...

How can I toggle the visibility of a div after the DOM has finished loading?

I was experimenting with a radio button on the interface linked to a property in the typescript file that controls the visibility of another div. However, I noticed that both *ngIf="isFooSelected" and [hidden]="!isFooSelected" only function upon initial pa ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

Prevent toggle button from activating panel expansion

Is there a way to add toggle buttons to the description section of an expansion panel without triggering the expansion panel when interacting with the buttons? I have included an example here. ...

VS Code is throwing an Error TS7013, while Typescript remains unfazed

In my Typescript/Angular project, I have the following interface: export interface MyInterface { new (helper: MyInterfaceHelpers); } After compiling the project, no errors are shown by the Typescript compiler. However, VSCode highlights it with squiggl ...

Displaying grouped arrays efficiently in Angular

I have received data from an API in the form of an array with objects structured like so: [ {"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1}, ...