有没有办法在没有猴子修补的情况下装饰/拦截Angular 4中的内置指令?

Tay*_*nan 7 javascript rxjs typescript angular

问题

我试图NgForm通过拦截onSubmit函数来添加内置指令的功能,以防止双重提交和无效提交,但我没有找到一种方法,没有猴子修补.

失败的尝试1:装饰器通过依赖注入

我真的不希望这与指令一起工作,因为它们不是真正的"提供者",但我还是尝试了它(无济于事).

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
}]
Run Code Online (Sandbox Code Playgroud)

工作尝试2:具有次要指令的猴子补丁

这很好用,但显然不理想.

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>;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有猴子修补的情况下装饰/拦截Angular 4中的内置指令?

Pie*_*Duc 1

您始终可以覆盖ngForm选择器并扩展该类NgForm

@Directive({
  selector: 'form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]',
})
export class CNgFormDirective extends NgForm {
 constructor(
      @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
      @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) {
    super(validators, asyncValidators);
  }

  onSubmit($event: Event): boolean {
    console.log(`I'm custom!`);

    return super.onSubmit($event);
  }
}
Run Code Online (Sandbox Code Playgroud)

工作栈