Reputation: 3177
On a form I have two (or more) categories of controls (currently only checkboxes):
<form [formGroup]="form">
<div class="category 1">
<mat-checkbox formControlName="cb1">Checkbox 1</mat-checkbox>
<mat-checkbox formControlName="cb2">Checkbox 2</mat-checkbox>
</div>
<div class="category 2">
<mat-checkbox formControlName="cb11">Checkbox 11</mat-checkbox>
<mat-checkbox formControlName="cb12">Checkbox 12</mat-checkbox>
</div>
...
</form>
Depending on other actions on the form, I need to control state of a category, i.e. enable/disable and check/uncheck all the controls. So I need a way to effectively iterate over a category. Currently I came up with a solution based on this answer, but this requires maintaining lists of names for each category.
Is there nicer/easier way to iterate over my categories?
Upvotes: 2
Views: 113
Reputation: 1384
If I understand your question correctly, you just need to enable/disable and check/uncheck the checkbox based on conditions right?
You can do something like this in the HTML itself
The <mat-checkbox>
has the [disabled]
and [checked]
attribute in its API. You can make use of it.
You can use *ngIf
to control the conditions.
It will turn out something like this:
<form [formGroup]="someForm"> // Don't name your form as 'form'. Not a good practice
<div class="category 1">
<mat-checkbox formControlName="cb1">Checkbox 1</mat-checkbox>
<mat-checkbox formControlName="cb2">Checkbox 2</mat-checkbox>
</div>
// Enable the second category only if both the above checkboxes are having a value
<div class="category 2" *ngIf="someForm.controls.cb1.value && someForm.controls.cb2.value">
<mat-checkbox
formControlName="cb11"
[disabled]="!someForm.controls.cb1.value" // This will be disabled if the value is false which will make the condition true
>
Checkbox 11
</mat-checkbox>
<mat-checkbox
formControlName="cb12"
[checked]="someForm.controls.cb1.value" // It will be checked only if cb1 is checked
>
Checkbox 12
</mat-checkbox>
</div>
...
</form>
You need not do it from the TS always. But if you want to do that in the TS, you will write something very similar:
this.someForm.controls.cb1.valueChanges.subscribe(data => {
if (data) {
this.someForm.controls.cb2.disable();
// After this you can remove the validators for the disabled field
this.someForm.controls.cb2.setValidators(null);
this.someForm.controls.cb2.updateValueAndValidity();
}
})
Upvotes: 1
Reputation: 530
High level - FormGroup
type has a controls
property which is an object of the following type {[key: string]: AbstractControl}
, see angular docs.
Technically you can iterate over object properties using for (const key in obj)
construct and manipulate your form controls.
Per Angular docs you can nest FormGroup
components to create the structure that you need to better manage the controls behavior.
Upvotes: 1