Home > Blockchain >  Why does ngSubmit event not working in angular?
Why does ngSubmit event not working in angular?

Time:11-25

I have created a directive to disable a form button after click but the (ngSubmit) event is not triggered. Without the directive click.disable works as expected. Any suggestions?

  <form [formGroup]="form" (ngSubmit)="submit()">
    <h3 class="text-center">Login</h3>
    <div>
      <input type="text" placeholder="Username" formControlName="user">
    </div>
    <br>
    <div>
      <input type="password" placeholder="Password" formControlName="password">
    </div>
    <br>
    <button class="btn-primary full-width d-block" click.disable>Login</button>
    <div class="login__forgot-pass">
      <a routerLink="">Forgot password?</a>
    </div>
  </form>
async submit() {
    const x = await this.auth.login(this.form)
    if (x.type === 'LoginSuccess') {
      this.redirectService.navigate('profile')
    } else {
      this.error = x.payload.message as string
    }
  }
@Directive({
  selector: '[click.disable]'
})
export class ClickDisableDirective {
  disabled = false

  @HostListener('click', ['$event'])
  hostClick(e: Event) {
    this.disabled = true
  }

  @HostBinding('disabled')
  get disable() {
    return this.disabled
  }
}

CodePudding user response:

Ok this is my approach

<form (ngSubmit)="submit()">

// some code

<button type="submit" [disabled]="isDisable">

in component.ts

isDisable = false;

submit = () => {
this.isDisable = true;

api.subscribe(res => {
//some response
this.isDisable = false;
}).error(err => {
// some error response
this.isDisable = false;
})

CodePudding user response:

If you wanted validate the form elements and once its valid you should enable the submit button. HTML

<form [formGroup]="form">
<button [disabled]="form.invalid"  (click)="submit($event)">Submit</button>

And on your submit method in the component you can add

submit(event: any) {
......
event.target.disabled = true;
}

This may work out.

  • Related