How to deal with double submit in Angular2

前端 未结 6 949
囚心锁ツ
囚心锁ツ 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:13

    This should work as well:

    or just (click) instead of (ngSubmit)

    update (see comments)

    update (use a directive)

    @Directive({
      selector: 'button[type=submit]'
    })
    class PreventDoubleSubmit {
    
      @HostBinding() disabled:boolean = false;
    
      @Input() valid:boolean = true;      
    
      @HostListener('click') 
      onClick() {
        if(!valid) {
          return;
        }
        this.disabled = true;
      }
    }
    

    and use it like

    You need to add it to the directives: [PreventDoubleSubmit] of the components where you want to use it or alternatively provide it globally

    provide(PLATFORM_DIRECTIVES, {useValue: [PreventDoubleSubmit], multi: true})
    

提交回复
热议问题