argos/dmp-frontend/src/app/form/pprogress-bar/progress-bar.component.ts

68 lines
2.5 KiB
TypeScript

import { VisibilityRulesService } from '../../utilities/visibility-rules/visibility-rules.service';
import { ViewEncapsulation } from '@angular/core';
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'app-progress-bar',
templateUrl: './progress-bar.component.html',
styles: ['.alwaysVisible .ui-progressbar-label { display:block!important; }'],
encapsulation: ViewEncapsulation.None
})
export class ProgressBarComponent implements OnInit {
@Input() formGroup: FormGroup;
@Input() public progressValueAccuracy = 1;
determinateProgressValue: number;
constructor(private visibilityRulesService: VisibilityRulesService) { }
public value = 0;
ngOnInit() {
this.calculateValueForProgressbar();
this.formGroup
.valueChanges
.subscribe(control => {
this.calculateValueForProgressbar();
});
}
calculateValueForProgressbar() {
const progressSoFar = this.countFormControlsWithValue(this.formGroup);
const total = this.getFormControlDepthLength(this.formGroup);
const perc = (progressSoFar / total) * 100;
this.value = Number.parseFloat(perc.toPrecision(this.progressValueAccuracy));
}
countFormControlsWithValue(form: FormGroup): number {
let value = 0;
Object.keys(form.controls).forEach(key => {
const control = form.controls[key];
if (control instanceof FormGroup) { value += this.countFormControlsWithValue(control); } else if (control instanceof FormArray) {
const formArray = (<FormArray>control);
for (let i = 0; i < formArray.length; i++) {
value += this.countFormControlsWithValue(<FormGroup>formArray.get('' + i));
}
} else if (key === 'value' && control.value != null && control.value !== '') { value++; }
});
return value;
}
getFormControlDepthLength(form: FormGroup): number {
let value = 0;
Object.keys(form.controls).forEach(key => {
const control = form.controls[key];
if (control instanceof FormGroup) { value += this.getFormControlDepthLength(control); } else if (control instanceof FormArray) {
const formArray = (<FormArray>control);
for (let i = 0; i < formArray.length; i++) {
if (<FormGroup>formArray.get('' + i).value && this.visibilityRulesService.checkElementVisibility(formArray.get('' + i).value.id)) {
value += this.getFormControlDepthLength(<FormGroup>formArray.get('' + i));
}
}
} else if (key === 'value' && this.visibilityRulesService.checkElementVisibility(form.controls['id'].value)) {
value++;
}
});
return value;
}
}