0
votes

In AngularJs I used to use the ng-submitted class for my form validation but it does not appear in Angular when you submit a form. I have written a directive that adds a class submitted to a form and removes it on reset

@Directive({
  selector: '[appForm]'
})
export class FormDirective implements OnDestroy {
  private subscription: Subscription;

  constructor(el: ElementRef, form: NgForm) {
    this.subscription = form.ngSubmit.subscribe(() => {
      el.nativeElement.classList.add('submitted');
    });
    form.onReset = () => {
      el.nativeElement.classList.remove('submitted');
    };
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

This works great when you reset the form with a reset button. The problem I am having is when I need to reset with values other than setting all the bindings to null I need to reset the form with the ngForm resetForm method but this does not trigger the onReset method and I can't find a way to tap into the form being reset this way.

https://stackblitz.com/edit/angular-u2rlx9

2

2 Answers

0
votes

NgForm directive has a submitted property that you can use. I don't see no need to use a directive in this case.

Instead you can use that boolean property for your needs, for whatever needs. If you want to set some class (like) in your stackblitz sample, you can use ngClass for that, that is the "angular way". You shouldn't manipulate the DOM unless really needed, and in this case it's definitely not needed as we can use angular bindings, which is recommended.

Here we can also use *ngIf:

<form #form="ngForm">
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
  <button type="button" (click)="form.resetForm()">Angular reset</button>
  <div *ngIf="form.submitted">Submitted</div>
  <div *ngIf="!form.submitted">Not submitted</div>
</form>

Your forked STACKBLITZ

-1
votes

You just need to call this to reset the form

resetForm() {
   this.form.reset();
}