I have the following problem: I have component with 2 check-boxes (using mat-checkbox) and this component is part of few of my pages. As an input I pass a object (appData) which contains an entry (key = ‘phases’) – with a string value which is the formControlName of the check box that needs to be marked as checked.
Here is the html part of the component:
<div [formGroup]="parentForm">
<ng-container *ngIf="phasesType === 'radio'">
<mat-label [ngClass]="fields['phases'].hasError('required') ? 'required' : ''">{{field.pivot.custom_label ?
field.pivot.custom_label : "Електрическата енергия ще бъде фактурирана по следните ценови тарифи"}}:</mat-label>
<mat-radio-group formControlName="phases" class="inline-radio-group">
<!-- [ngClass]="field.pivot.field_class ? field.pivot.field_class : 'inline-radio-group'" -->
<mat-radio-button class="radio-button no-radius" [value]="'single'" *ngIf="showSingle">
<span
[style.color]="fields['phases'].hasError('required') && fields['isSubmitted'].value === true ? 'red' : ''">монофазно</span>
</mat-radio-button>
<mat-radio-button class="radio-button no-radius" [value]="'three'" *ngIf="showThree">
<span
[style.color]="fields['phases'].hasError('required') && fields['isSubmitted'].value === true ? 'red' : ''">трифазно</span>
</mat-radio-button>
<!-- <mat-radio-button class="radio-button no-radius" [value]="'mixed'" *ngIf="showMixed">-->
<!-- <span-->
<!-- [style.color]="fields['phases'].hasError('required') && fields['isSubmitted'].value === true ? 'red' : ''">монофазно-->
<!-- и трифазно</span>-->
<!-- </mat-radio-button>-->
</mat-radio-group>
</ng-container>
<ng-container *ngIf="phasesType !== 'radio'">
<div class="row" formGroupName="phases">
<mat-label [ngClass]="fields['phases'].hasError('atLeastOneChecked') ? 'required' : ''">{{field.pivot.custom_label
?
field.pivot.custom_label : "Електрическата енергия ще бъде фактурирана по следните ценови тарифи"}}:</mat-label>
<div class="col-sm-3">
<mat-checkbox class="" formControlName="single">монофазно</mat-checkbox>
</div>
<div class="col-sm-3">
<mat-checkbox class="" formControlName="three">трифазно</mat-checkbox>
</div>
</div>
</ng-container>
</div>
And here is the ts file contents:
import { Component, EventEmitter, Inject, Input, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ApplicationFields } from "../../interfaces/application-fields";
import { FillFieldsService } from "../../services/fill-fields.service";
import { ValidationService } from "../../../shared/services/validation.service";
import { VoltageLevelsKvComponent } from '../voltage-levels-kv/voltage-levels-kv.component';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'app-phases',
templateUrl: './phases.component.html',
styleUrls: ['./phases.component.scss']
})
export class PhasesComponent {
@Input() showSingle: boolean = true;
@Input() showThree: boolean = true;
@Input() showMixed: boolean = true;
@Input() phasesType: string = 'checkbox';
@Input() conditions = {};
@Input() field: ApplicationFields;
@Input() parentForm: FormGroup;
@Input() appData: {};
@Output() parentFormChange = new EventEmitter<FormGroup>();
current: { "single": boolean, "three": boolean } = { "single": null, "three": null };
constructor(private validation: ValidationService, private fb: FormBuilder, private fillFieldsService: FillFieldsService, @Inject(DOCUMENT) document: Document) {
}
ngOnInit(): void {
if (this.conditions) {
const mapped = Object.keys(this.conditions).map(key => ({ prop: key, value: this.conditions[key] }));
mapped.forEach(value => {
this[value.prop] = value.value;
});
}
this.parentForm = this.fb.group({
...this.parentForm.controls,
"phases": this.getPhasesValidatorsByType()
});
this.parentFormChange.emit(this.parentForm);
this.parentForm.patchValue(this.appData);
if (this.phasesType === "checkbox") {
let phases = { "single": null, "three": null };
if (typeof this.appData['phases'] === "string") { // this.appData['phases'] = 'single' || 'three'
phases[this.appData['phases']] = true; // here phases = { "single": true, "three": null } for example depending on the previous line
}
this.parentForm.controls['phases'].setValue(phases, { emitEvent: false }); // does not update the value of the form and both 'single & three' are null
} else {
this.parentForm.controls['phases'].setValue(this.appData['phases'], { emitEvent: false });
}
if (this.parentForm.get('electricity_meters')) {
this.fields['electricity_meters'].valueChanges.subscribe(val => {
let addMax = false;
if (val < 2) {
addMax = true;
}
this.validation.powerProvidedMaxValidator(addMax, 13, this.parentForm);
});
}
this.current = this.fields['phases'].value
this.fields['phases'].valueChanges.subscribe(val => {
console.log(this.current, 1);
let typeOf = typeof val;
let single = typeOf === "object" ? val['single'] : val === "single";
let three = typeOf === "object" ? val['three'] : val === "three";
if (this.parentForm.get('electric_meter') && this.parentForm.get('application_type_type')?.value !== "SUD") {
let power = this.parentForm.get('installed_peak_power')?.value;
let voltageLevel = this.parentForm.get('voltage_level')?.value;
let response = this.fillFieldsService.fillElectricField(power, val, voltageLevel);
this.parentForm.get('electric_meter').setValue(response);
}
if (three) {
if (this.parentForm.get('voltage_level')?.value === "first") {
this.parentForm.get('voltage_level')?.setValue(null);
}
}
if (this.parentForm.get("power_provided") && !this.parentForm.get("future_clients") && !this.appData['future_clients']) {
let addMax = false;
if (single && !three) {
addMax = true;
}
this.validation.powerProvidedMaxValidator(addMax, 13, this.parentForm);
} else {
this.validation.powerProvidedMaxValidator(single && !three, 13, this.parentForm);
}
if (this.parentForm.get('future_clients') && this.appData['object_type'] != "expanding") {
let fcSingle = false;
let fcThree = false;
let fcTotal = 0;
this.fields['future_clients'].value.forEach(client => {
fcTotal += client.count;
if (client.phase === "монофазно") {
fcSingle = true;
} else if (client.phase === "трифазно") {
fcThree = true;
}
});
if (fcSingle && !fcThree) {
this.validation.powerProvidedMaxValidator(true, fcTotal * 13, this.parentForm);
} else {
this.validation.powerProvidedMaxValidator(false, 13, this.parentForm);
}
if (this.current['single'] === null && this.current['three'] === null) {
fcThree = val['three'];
fcSingle = val['single'];
} else if (fcTotal === 0 && !fcSingle && !fcThree) {
fcThree = !this.current['three'];
fcSingle = !this.current['single'];
}
if (fcTotal == 0) {
fcThree = !fcSingle;
}
console.log(this.fields['future_clients'].value.length, "Expanding")
if (this.fields['future_clients'].value.length < 2 && this.appData['object_type'] != "expanding") {
this.parentForm.get('phases').setValue({ "single": fcSingle, "three": fcThree }, { emitEvent: false });
this.current = { "single": fcSingle, "three": fcThree };
}
}
if (this.parentForm.get('electricity_meters')) {
let valEM = this.parentForm.get('electricity_meters').value !== '' ? this.parentForm.get('electricity_meters').value : 1;
let addMax = false;
let maxAmount = valEM * 13;
if (this.phasesType === "checkbox") {
if (single && three && (valEM === '' || valEM < 2)) {
this.parentForm.get('phases').setValue({ "single": true, "three": false });
}
}
if (single && !three) {
addMax = true;
}
this.validation.powerProvidedMaxValidator(addMax, maxAmount, this.parentForm);
this.parentForm.get('electricity_meters').valueChanges.subscribe(val => {
let valEM = this.parentForm.get('electricity_meters').value !== '' ? this.parentForm.get('electricity_meters').value : 1;
let valP = this.parentForm.get('phases').value;
let addMax = false;
let maxAmount = valEM * 13;
let single = typeof valP === "object" ? valP['single'] : valP === "single";
let three = typeof valP === "object" ? valP['three'] : valP === "three";
if (single && !three) {
addMax = true;
}
this.validation.powerProvidedMaxValidator(addMax, maxAmount, this.parentForm);
});
}
if (this.appData["application_url"] == "OD-EE-153" || this.appData["application_url"] == "OD-EP-126") {
if (this.current['single'] == true) {
this.current['single'] = false;
this.current['three'] = true;
this.parentForm.controls['phases'].setValue(this.current, { emitEvent: false });
}
else {
this.current['single'] = true;
this.current['three'] = false;
this.parentForm.controls['phases'].setValue(this.current, { emitEvent: false });
}
}
if (this.parentForm.get('price_list')) {
if (this.current['single']) {
this.parentForm.get('price_list')?.setValue("5310");
} else {
this.parentForm.get('price_list')?.setValue("5311");
}
}
// console.log(this.parentForm.get('voltage_level').disable())
if (this.current['single']) {
this.parentForm.get('voltage_level')?.setValue("first");
} else {
this.parentForm.get('voltage_level')?.setValue("second");
}
console.log(this.current, 2);
});
}
getPhasesValidatorsByType() {
if (this.phasesType === "radio") {
return ["", Validators.required];
} else {
return this.fb.group({
"single": [this.appData['phases'] ? this.appData['phases']['single'] : null],
"three": [this.appData['phases'] ? this.appData['phases']['three'] : null],
}, { validators: this.validation.atLeastOneCheckedValidator });
}
}
get fields() {
return this.parentForm.controls;
}
}
As you can see: @Input() phasesType: string = 'checkbox';
means I always enter this part of the html:
<ng-container *ngIf="phasesType !== 'radio'">
<div class="row" formGroupName="phases">
<mat-label [ngClass]="fields['phases'].hasError('atLeastOneChecked') ? 'required' : ''">{{field.pivot.custom_label
?
field.pivot.custom_label : "Електрическата енергия ще бъде фактурирана по следните ценови тарифи"}}:</mat-label>
<div class="col-sm-3">
<mat-checkbox class="" formControlName="single">монофазно</mat-checkbox>
</div>
<div class="col-sm-3">
<mat-checkbox class="" formControlName="three">трифазно</mat-checkbox>
</div>
</div>
</ng-container>
My problem (my suspicion) is in this part of the TS logic:
if (this.phasesType === "checkbox") {
let phases = { "single": null, "three": null };
if (typeof this.appData['phases'] === "string") { // this.appData['phases'] = 'single' || 'three'
phases[this.appData['phases']] = true; // here phases = { "single": true, "three": null } for example depending on the previous line
}
this.parentForm.controls['phases'].setValue(phases, { emitEvent: false }); // does not update the value of the form and both 'single & three' are null
} else {
this.parentForm.controls['phases'].setValue(this.appData['phases'], { emitEvent: false });
}
As you can see I’ve put 3 comments what is the value of the incoming appData[‘phases’], then what the value of the phases variable is etc.
For me it seems the setValue() function does not update the component thus the form and both check boxes remain unchecked.
If anyone have an idea why this is happening I will be grateful for any advice.
Thanks in advance.