Problem
I am trying to add functionality to the built-in NgForm directive by intercepting the onSubmit function in order to prevent double-submission and invalid submission, but I haven't been able to find a way to do so without monkey patching.
Failed Attempt 1: Decorator via Dependency Injection
I didn't really expect this to work with directives since they aren't really "providers", but I tried it anyway (to no avail).
import { Injectable } from '@angular/core';
import { NgForm } from '@angular/forms';
@Injectable()
export class NgFormDecorator extends NgForm {
constructor() {
super(null, null);
}
onSubmit($event: Event): boolean {
// TODO: Prevent submission if in progress
return super.onSubmit($event);
}
}
// Module configuration
providers: [{
provide: NgForm,
useClass: NgFormDecorator
}]
Working Attempt 2: Monkey Patch with Secondary Directive
This works great but is obviously not ideal.
import { Directive, Output, EventEmitter } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/finally';
import { noop } from 'rxjs/util/noop';
@Directive({
selector: 'form',
exportAs: 'NgFormExtension'
})
export class NgFormExtensionDirective {
private onSubmitBase: ($event: Event) => void;
submitting: boolean;
constructor(private ngForm: NgForm) {
this.onSubmitBase = ngForm.onSubmit;
ngForm.onSubmit = this.onSubmit.bind(this);
}
private onSubmit($event: FormSubmitEvent): boolean {
if (this.submitting || this.ngForm.invalid) {
return false;
}
this.submitting = true;
const result = this.onSubmitBase.call(this.ngForm, $event);
if ($event.submission) {
$event.submission
.finally(() => this.submitting = false)
.subscribe(null, noop);
} else {
this.submitting = false;
}
return result;
}
}
export class FormSubmitEvent extends Event {
submission: Observable<any>;
}
Question
Is there a way to decorate/intercept a built-in directive in Angular 4 without monkey patching?