File

src/lib/directives/form-submit.directive.ts

Extends

ConfirmClick

Implements

OnDestroy

Metadata

Index

Methods
Inputs
Outputs
Accessors

Constructor

constructor(formDirective: FormDirective, router: Router | null)
Parameters :
Name Type Optional
formDirective FormDirective No
router Router | null No

Inputs

navigateAfterSubmit
Type : string[]
resetAfterSubmit
Type : boolean | string
type
Type : string
Default value : 'button'

Outputs

afterSubmit
Type : EventEmitter

Methods

Protected execute
execute()
Returns : void

Accessors

resetAfterSubmit
setresetAfterSubmit(value: boolean | string)
Parameters :
Name Type Optional
value boolean | string No
Returns : void
import {
  Directive,
  EventEmitter,
  HostBinding,
  Inject,
  Input,
  OnDestroy,
  Optional,
  Output,
} from '@angular/core';
import { Router } from '@angular/router';
import { ConfirmClick } from '@rxap/directives';
import {
  clone,
  coerceBoolean,
} from '@rxap/utilities';
import { Subscription } from 'rxjs';
import {
  take,
  tap,
} from 'rxjs/operators';
import { FormDirective } from './form.directive';

@Directive({
  selector: '[rxapFormSubmit]',

  host: {
    '(click)': 'onClick()',
    '(confirmed)': 'onConfirm()',
  },
  standalone: true,
})
export class FormSubmitDirective extends ConfirmClick implements OnDestroy {

  @HostBinding('type')
  @Input()
  public type = 'button';

  @Input()
  public set resetAfterSubmit(value: boolean | '') {
    this._resetAfterSubmit = coerceBoolean(value);
  }

  @Input()
  public navigateAfterSubmit?: string[];

  @Output()
  public afterSubmit = new EventEmitter();

  private _resetAfterSubmit = false;

  private subscription?: Subscription;

  constructor(
    @Inject(FormDirective) private readonly formDirective: FormDirective,
    @Optional()
    @Inject(Router)
    private readonly router: Router | null = null,
  ) {
    super();
  }

  protected execute() {
    this.formDirective.form.markAllAsDirty();
    this.formDirective.form.markAllAsTouched();
    this.formDirective.cdr.markForCheck();
    this.subscription = this.formDirective.rxapSubmit.pipe(
      take(1),
      tap(value => {
        const clonedValue = clone(value);
        this.afterSubmit.emit(clonedValue);
        if (this._resetAfterSubmit) {
          this.formDirective.reset();
        }
        if (this.navigateAfterSubmit) {

          if (!this.router) {
            throw new Error('Could not resolve the router!');
          }

          return this.router.navigate(this.navigateAfterSubmit);
        }
        return Promise.resolve();
      }),
    ).subscribe();
    this.formDirective.onSubmit(new Event('submit'));
  }

  public ngOnDestroy() {
    this.subscription?.unsubscribe();
  }

}

results matching ""

    No results matching ""