Is there any way to decorate / intercept the built-in directive in Angular 4 without patch monkeys?

Problem

I am trying to add functionality to the built-in NgForm directive by intercepting the onSubmit function to prevent double submission and invalid transmission, but I could not find a way to do this without monkey patches.

Failed attempt 1: Decorator through dependency injection

I really did not expect this to work with directives, since they are not "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 }] 

Work Attempt 2: Monkey Patch with Additional Directive

This works great, but obviously not perfect.

 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 any way to decorate / intercept the built-in directive in Angular 4 without monkey patches?

+5
source share

Source: https://habr.com/ru/post/1272165/


All Articles