Home > Back-end >  How to select form?
How to select form?

Time:10-19

A similar question already exists but is not the same.

I need global solution probably using directive or whatever?

I have I form

<form (submit)="onSubmit()">
  <input type="text">
  <button type="submit>
</form>

Ok solution for this is not accepted for my use case:

submitted: false;

onSubmit(){
 this.submitted = true;
}

and set on button

[disabled]="submitted"

I need global solution... I start but don't know what next...

@Directive({ selector: 'form' })

export class PreventSubmitFewTimesDirective implements OnInit {

  constructor(
    private formSelector: ElementRef, 
  ) {}

   ngOnInit() {}  

  @HostListener('submit')
  onSubmit(evt: KeyboardEvent) { 
    .... // 
  }

I am target every form on submit but need best solution.

CodePudding user response:

What you could do is the following:

// Targets every form with the 'disableAfterSubmit' directive, not every form (in case you want one or two forms not to have this behavior)
@Directive({ selector: 'form[disableAfterSubmit]' })

export class PreventSubmitFewTimesDirective {

  constructor(private formSelector: ElementRef) {}

  @HostListener('submit')
  onSubmit(evt: KeyboardEvent) { 
    // Get the submit button with a query selector
    const button = this.el.nativeElement.querySelector('button[type="submit"]');
    // Disable it
    button.disabled = true;
  }

Note that with this solution, there is no way to re-enable the submit button.

CodePudding user response:

I don't think a global solution is the best approach but if you really have to do it, I would try out to save to localstorage then read from that. However i wouldn't recommend it..

  • Related