包含内置禁用 /重新启用的按钮组件(防止双提交!)



处理表单组件本身上的所有'禁用'验证逻辑是一个好的经验法则吗?那听起来对吗?

我真的只是想找到一种在不重复每个形式组件的情况下在应用程序上共享"禁用"逻辑的方法,但我想这是做事的正确方法?有人可以验证吗?

我想创建一个可重复使用的提交按钮组件。此提交按钮组件应像其他任何提交按钮组件一样起作用,除了一件事...

单击后,提交按钮需要"禁用自身"。那应该很容易正确。但是,这里的摩擦是,"呼叫"完成后,按钮还需要"重新启用自身"。(如果存在错误,或者该应用程序需要在第一个完成后允许其他操作等(。

我想在组件内部存在100%的"该"逻辑,以便我可以轻松地在应用程序中的任何地方重复使用它。

我认为这有点容易,但是我想我仍然缺少一些东西...我想这个想法是使用@input((最好是(或输出(,以将某些"异步回调类型"传递给按钮控件本身...

这样,按钮可以对"事物的异步回调类型"做出反应,并使用回调处理程序重新启用。

感谢提前的帮助!

我写了一个抽象类

import { ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { FormGroup, FormGroupDirective } from '@angular/forms';
export abstract class FormBase<T = any> {
    @Input() isSubmitting: boolean;
    @Output('onSubmit') _submit = new EventEmitter<T>();
    @ViewChild(FormGroupDirective, { static: true })
    ngForm: FormGroupDirective;
    @ViewChild('submitButton', { static: true }) button: ElementRef;
    form: FormGroup;
    onSubmit(): void {
        if (this.isFormValid()) this._submit.emit(this.getFormValue());
    }
    submit(): void {
        if (!this.button || !this.button.nativeElement) return;
        this.button.nativeElement.click();
    }
    reset(value?: any) {
        this.ngForm.resetForm(value);
    }
    isFormValid(): boolean {
        return this.form.valid;
    }
    getFormValue(): T {
        return this.form.value;
    }
    shouldDisable(): boolean {
        return (
            this.isSubmitting ||
            ((this.form.invalid || this.form.pending) &&
                (this.ngForm ? this.ngForm.submitted : true))
        );
    }
}

component.ts

import { FormBase } from 'path';
@Component({
    ...
})
export class FormComponent extends FormBase {
    constructor(formBuilder: FormBuilder) {
        super();
        this.form = formBuilder.group({
            username: ['', Validators.required],
            password: ['', Validators.required],
        });
    }
}

component.html

<form (ngSubmit)="onSubmit()" [formGroup]="form">
    <mat-form-field>
        <mat-label>Username</mat-label>
        <input matInput type="text" formControlName="username" />
    </mat-form-field>
    <mat-form-field>
        <mat-label>Password</mat-label>
        <input matInput type="text" formControlName="password" />
    </mat-form-field>
    <button [disabled]="shouldDisable()" mat-flat-button color="primary">
        Submit
    </button>
</form>

您的表格组件基本上是从该类延伸的,该课程应在99%的时间内工作。如果您的组件需要一些非常具体的功能,例如在禁用按钮时更改或其他功能,则可以简单地覆盖FormComponent中的方法。

最新更新