How to deal with double submit in Angular2

前端 未结 6 953
囚心锁ツ
囚心锁ツ 2021-02-02 11:30

If I click fast on my submit-button the form is submitted two or more times. My thought was to prevent this with the disabled attribute, but I need variable disableButon

6条回答
  •  一整个雨季
    2021-02-02 12:29

    You could have a base component exposes a get which tells if the component is busy. This get can be used on the template to then disable or enable the button. For something which does an async call the base component has a protected method which takes in a function call. e.g.

    Base Component

    export abstract class BusyComponent {
        private _isBusy = false;
    
        get isBusy(): boolean {
            return this._isBusy;
        }
    
        protected async performBusyTask(busyFunction: () => Promise) {
            this._isBusy = true;
            try {
                return await busyFunction();
            } finally {
                this._isBusy = false;
            }
        }
    }
    

    Child Component

    class BusyComponentChild extends BusyComponent {
    
        constructor(private dependency: Dependency) {
            super();
        }
    
        doSomethingAsync(): Promise {
            return this.performBusyTask(() => this.dependency.doSomethingAsync());
        }
    }
    

    Template

    
    

提交回复
热议问题