import { Component, OnInit, OnDestroy } from '@angular/core'; import { Asset, TypeDepreciation, YearMonth, AssetLifeChange } from '../assets/asset'; import { ReactiveFormsModule, FormBuilder, FormGroup, FormArray, ValidatorFn, ValidationErrors, AbstractControl } from '@angular/forms'; @Component({ selector: 'app-fixed-asset', standalone: true, imports: [ReactiveFormsModule], template:`

Lista środków trwałych

@for( assetFormGroup of assetFormArray.controls; track $index ) { }
Numer inwentarzowy Wartość Metoda amortyzacji
`, styleUrl: './fixed-asset.component.css' }) export class FixedAssetComponent { static STORAGE_KEY = "fixed_assets"; static indexNr = 1; TypeDepreciation = TypeDepreciation; assetFormArray : FormArray; constructor( private fb: FormBuilder ){ this.assetFormArray = this.fb.array([]) } ngOnInit(): void { const savedAssets = localStorage.getItem( FixedAssetComponent.STORAGE_KEY) ; if( savedAssets ) { this.assetsToControls( JSON.parse( savedAssets ) ); } } ngOnDestroy(): void { localStorage.setItem( FixedAssetComponent.STORAGE_KEY, JSON.stringify( this.controlsToAssets() ) ); } private assetsToControls( assetsArray: [ string, Asset ][]) { const assetsMap = new Map( assetsArray ); assetsMap.forEach( (asset, key) => { this.addRow( key, asset.life[0].initial ); }); } private controlsToAssets(): [string, Asset][] { const assets = new Map(); this.assetFormArray.controls.forEach( control => { const nrInv = control.get('nrInv')?.value; const initialValue = control.get('initialValue')?.value; const yearMonth = YearMonth.today(); const asset = new Asset( yearMonth ); const assetLifeChange = new AssetLifeChange( yearMonth, initialValue, 0, 0 ); asset.addChange( assetLifeChange ); assets.set( nrInv, asset ); }); return Array.from( assets.entries() ); } delete( index : number ){ this.assetFormArray.removeAt( index ); } addNew(){ this.addRow( "NrInv" + FixedAssetComponent.indexNr++, 1000 ); } addRow( nrInv_:string, initial_: number ):void{ const newRow = this.fb.group({ nrInv : [ nrInv_ ], initialValue : [ initial_ ], }); // typeDepreciation : [ TypeDepreciation.linear ], // depreciationRate : [ 10 ], // year_month : [ year_month ] this.assetFormArray.push( newRow ); } // uniqueColumnValidator(): ValidatorFn { // return (control: AbstractControl): ValidationErrors | null => { // const values = this.assetFormArray.map(field => field.value) || []; // const uniqueValues = new Set(values); // return uniqueValues.size !== values.length ? { uniqueColumn: true } : null; // }; // } }