ChangeDetectionStrategy.OnPush

This commit is contained in:
Artur 2024-11-15 00:48:54 +01:00
parent 35c83ad335
commit b3987347fe
1 changed files with 10 additions and 6 deletions

View File

@ -1,10 +1,11 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { ReactiveFormsModule, FormGroup, Validators, FormControl, FormArray } from '@angular/forms';
import { DecimalPipe } from '@angular/common';
import {Asset, Positions, AssetPlanPosition, TypeDepreciation, YearMonth, AssetLifeChange, AssetDepreciationMethod, YearMonthUtil } from '../assets/asset';
import {AssetService} from '../assets/service/asset.service'
import {TranslateModule} from "@ngx-translate/core";
import { debounceTime } from 'rxjs/operators';
interface FormValues {
initialValueAsset: number;
@ -15,6 +16,7 @@ interface FormValues {
}
@Component({
selector: 'app-asset-calculator',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [ DecimalPipe, ReactiveFormsModule, TranslateModule ] ,
templateUrl: "asset-calculator.component.html",
@ -39,9 +41,9 @@ export class AssetCalculatorComponent implements OnInit, OnDestroy{
[key in keyof FormValues]: FormControl<FormValues[key]>
});
constructor(private assetService : AssetService){
this.assetsDepreciationFormGroup.valueChanges.subscribe( (value) => this.calculate() );
this.lifeFormArray.valueChanges.subscribe( (value) => this.calculate() );
constructor(private assetService : AssetService, private cdr: ChangeDetectorRef){
this.assetsDepreciationFormGroup.valueChanges.pipe(debounceTime(300)).subscribe( (value) => this.calculate() );
this.lifeFormArray.valueChanges.pipe(debounceTime(300)).subscribe( (value) => this.calculate() );
}
@ -75,6 +77,7 @@ export class AssetCalculatorComponent implements OnInit, OnDestroy{
} );
});
}
this.cdr.detectChanges(); // Immediately update the view after patching
}
@ -105,9 +108,9 @@ export class AssetCalculatorComponent implements OnInit, OnDestroy{
this.assetService.calculate(asset).subscribe(positions => {
this.amortizations = positions;
this.calculateToValues(positions);
this.cdr.markForCheck(); // Trigger change detection
});
localStorage.setItem('assetForCalculator', JSON.stringify(asset));
}
calculateForAsset( asset : Asset ) {
@ -155,11 +158,12 @@ export class AssetCalculatorComponent implements OnInit, OnDestroy{
this.lifeFormArray.push(newFormGroup);
// this.lifeSignal.set( this.lifeFormArray );
this.cdr.markForCheck(); // Notify Angular of change
}
removeChange(index: number) {
this.lifeFormArray.removeAt(index);
this.cdr.markForCheck(); // Trigger detection after removal
}
}