import { Component , EventEmitter , Input , OnInit , Output } from "@angular/core" ; import { Entity } from "../../../entity/model/entity" ; import { OperationType } from "../../../permissions/entity-permissions.service" ; import { FormFieldConfig } from "./FormConfig" ; import { FormGroup } from "@angular/forms" ; import { EntityFormService } from "../entity-form.service" ; import { AlertService } from "../../../alerts/alert.service" ; @ Component ( { selector : "app-entity-form" , templateUrl : "./entity-form.component.html" , styleUrls : [ "./entity-form.component.scss" ] , } ) export class EntityFormComponent implements OnInit { /**
     * The entity which should be displayed and edited
     */ @ Input ( ) entity : Entity ; /**
     * Whether the form should be opened in editing mode or not
     */ @ Input ( ) editing = false ; param columns @ Input ( ) set columns ( columns ) { this . _columns = columns . map ( ( row ) => row . map ( ( field ) => { if ( typeof field === "string" ) { return { id : field } ; } else { return field ; } } ) ) ; } _columns : FormFieldConfig [ ] [ ] = [ ] ; /**
     * This will be emitted whenever changes have been successfully saved to the entity.
     */ @ Output ( ) onSave = new EventEmitter < Entity > ( ) ; /**
     * This will be emitted whenever the cancel button is pressed.
     */ @ Output ( ) onCancel = new EventEmitter < void > ( ) ; operationType = OperationType ; form : FormGroup ; constructor ( private entityFormService , private alertService ) { } ngOnInit ( ) { this . buildFormConfig ( ) ; if ( this . editing ) { this . switchEdit ( ) ; } } switchEdit ( ) { if ( this . form . disabled ) { this . form . enable ( ) ; } else { this . form . disable ( ) ; } } async save ( ) { try { await this . entityFormService . saveChanges ( this . form , this . entity ) ; this . onSave . emit ( this . entity ) ; this . switchEdit ( ) ; } catch ( err ) { this . alertService . addWarning ( err . message ) ; } } cancel ( ) { this . onCancel . emit ( ) ; this . buildFormConfig ( ) ; } private buildFormConfig ( ) { const flattenedFormFields = new Array < FormFieldConfig > ( ) . concat ( ... this . _columns ) ; this . entityFormService . extendFormFieldConfig ( flattenedFormFields , this . entity ) ; this . form = this . entityFormService . createFormGroup ( flattenedFormFields , this . entity ) ; this . form . disable ( ) ; } }