File

packages/ui/src/lib/form/form.service.ts

Description

This service is the interface between Angular Forms and ec.components core classes.

Index

Properties
Methods

Constructor

constructor(symbol: SymbolService)
Parameters :
Name Type Optional
symbol SymbolService No

Methods

Public addField
addField(field: Field, form: Form, group: FormGroup)

adds a new field to a form. handles form group and control

Parameters :
Name Type Optional
field Field No
form Form<any> No
group FormGroup No
Returns : void
getFormLabel
getFormLabel(form: FormComponent, label)

Returns label for given form (e.g. Edit label)

Parameters :
Name Type Optional Default value
form FormComponent<any> No
label No this.symbol.resolve('resource.generic')
Returns : string
Public getGroup
getGroup(form: Form)

Initializes the form group from the form fields

Parameters :
Name Type Optional
form Form<any> No
Returns : any
getValidators
getValidators(field: Field)

Extracts all validators from a given Field instance.

Parameters :
Name Type Optional
field Field No
Returns : ValidatorFn[]
isReadOnly
isReadOnly(field, form)

Returns true if the field should be readOnly, depending on its config and the form state.

Parameters :
Name Optional
field No
form No
Returns : any
Public shouldBePartOfForm
shouldBePartOfForm(field, form)

Returns true if the field should be included in the form. Decides based on field config values form, edit and create

Parameters :
Name Optional
field No
form No
Returns : boolean
validateFactory
validateFactory(field: Field)

Returns a Validation function from the given field (using field.validate)

Parameters :
Name Type Optional
field Field No
Returns : ValidationErrors | null

Properties

Public symbol
Type : SymbolService
import { Injectable } from '@angular/core';
import { Form, Field } from '@ec.components/core';
import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { SymbolService } from '../symbol/symbol.service';
import { FormComponent } from '../form/form.component';

/** This service is the interface between Angular Forms and ec.components core classes. */
@Injectable()
export class FormService {
  constructor(public symbol: SymbolService) { }

  /** Returns true if the field should be included in the form.
   * Decides based on field config values form, edit and create */
  public shouldBePartOfForm(field, form) {
    if (field.create === false && !form.getBody()) {
      return false;
    }
    if (field.edit === false && !!form.getBody()) {
      return false;
    }
    return field.form !== false;
  }

  /** Initializes the form group from the form fields*/
  public getGroup(form: Form<any>) {
    const controls = {};
    form.fields
      .filter((field) => this.shouldBePartOfForm(field, form))
      .forEach((field) => {
        const validators = this.getValidators(field);
        let value = form.getValue(field.property);
        value = value === undefined ? null : value;
        controls[field.property] = new FormControl(
          {
            value,
            disabled: this.isReadOnly(field, form),
          },
          validators,
        );
        // TODO use { updateOn: blur } when updating to angular 5.0.0
        // see https://github.com/angular/angular/commit/333a708bb632d4258ecb5fd4a0e86229fe9d26e4
      });
    return new FormGroup(controls);
  }

  /** adds a new field to a form. handles form group and control */
  public addField(field: Field, form: Form<any>, group: FormGroup) {
    console.warn('addField is experimental!');
    const validators = this.getValidators(field);
    const control = new FormControl({ value: form.getValue(field.property) }, validators);
    group.addControl(field.property, control);
  }

  /** Extracts all validators from a given Field instance. */
  getValidators(field: Field): ValidatorFn[] {
    const validators = [];
    if (field.required) {
      validators.push(Validators.required);
    }
    if (field.validate) {
      validators.push(this.validateFactory(field));
    }
    return validators;
  }

  /** Returns a Validation function from the given field (using field.validate) */
  validateFactory(field: Field): ValidationErrors | null {
    return (control: AbstractControl) => {
      if (!field.validate) {
        return;
      }
      const error = field.validate(control.value, field);
      if (error) {
        return {
          custom: error,
        };
      }
    };
  }

  /** Returns true if the field should be readOnly, depending on its config and the form state. */
  isReadOnly(field, form) {
    return field.disabled || (field.readOnly && form && !!form.getBody());
  }

  /** Returns label for given form (e.g. Edit label) */
  getFormLabel(form: FormComponent<any>, label = this.symbol.resolve('resource.generic')) {
    if (!form || !form.form) {
      return '';
    }
    return `${this.symbol.resolve('resource.' + (form.form.isEditing() ? 'edit' : 'create'))}
    ${label} ${form.form.display() ? `"${form.form.display()}"` : ''}`;
  }
}

result-matching ""

    No results matching ""