I have a data gathering component which includes 'cancel' button to cancel the whole process. The problem is, if some of the HTML input fields which are validated by Angular 2 validators have focus, and are not valid, and I press the cancel button, the component is not removed. Instead, validators will fire and the cancel button press will be ignored. I have to press it for the second time, after the validators complain, to make the component disappear.Cancel button itself simply triggers routing away from the component. Relevant code:
component.html
<form [formGroup]="addReminderForm" (ngSubmit)="onSubmit(addReminderForm.value)">
<input type="text" [formControl]="addReminderForm.controls['text']" />
<div class="error" *ngIf="addReminderForm.controls['text'].hasError('required') &&
addReminderForm.controls['text'].touched">You must enter reminder text</div>
<button type="submit" [disabled]="!addReminderForm.valid" >Add Reminder</button>
</form>
<button (click)="cancel()">Cancel</button>
component.ts:
ngOnInit() {
this.addReminderForm = this.fb.group({
'text': ['', Validators.compose([Validators.required, Validators.maxLength(20)])]
});
}
cancel() {
// Simply navigate back to reminders view
this.router.navigate(['../'], { relativeTo: this.route }); // Go up to parent route
}
I have no idea why this happens. Any ideas?
ng-dirty The field has been modified. ng-valid The field content is valid. ng-invalid The field content is not valid. ng-valid-key One key for each validation.
import { FormsModule } from '@angular/forms'; In Reactive forms, we need to import FormGroup from '@angular/forms' . After importing the above-mentioned modules in the respective approach, angular forms module provides an inbuilt method called reset(). We can use the method and we can reset the form.
1. setValidators() method removes all the previous/default validators from form control. For example, let's suppose during form initialization, you set maxLength and minLength validators for County .
Create a new Angular component with an initial form layout. Add data properties to bind for each form control and add an attribute to each form-input control. Show/hide validation messages. Handle form submit using ngSubmit .
Change the event from (click) to (mousedown). Mousedown is invoked before blur event.
So instead of this <button (click)="cancel()">Cancel</button>
try this: <button (mousedown)="cancel()">Cancel</button>
Try using button type="reset" like:
<form [formGroup]="heroForm" (ngSubmit)="onSubmit()" novalidate>
...
<div>
<button type="submit" [disabled]="heroForm.pristine">Save</button>
<button type="reset" (click)="revert()"[disabled]="heroForm.pristine">Revert o Cancel</button>
</div>
</form>
In your component class:
revert() { this.ngOnChanges(); }
For more information in https://angular.io/guide/reactive-forms
I hope to help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With