libs/core/dynamic-form/checkbox/src/checkbox.component.ts
DfBaseComponent<DfCheckboxConfig | DfCheckboxGroupConfig>
| changeDetection | ChangeDetectionStrategy.OnPush |
| selector | df-checkbox |
| styleUrls | ./checkbox.component.scss |
| templateUrl | ./checkbox.component.html |
Properties |
Methods |
Inputs |
Outputs |
| control | |
Type : UntypedFormControl
|
|
Default value : new UntypedFormControl()
|
|
|
Inherited from
DfBaseComponent
|
|
| config | |
Type : C
|
|
| Required : true | |
|
Inherited from
DfBaseComponent
|
|
|
The configuration object for this formfield. Note that derived formfield components should extend the |
|
| formAclPath | |
Type : string
|
|
|
Inherited from
DfBaseComponent
|
|
| isAclHandled | |
Type : boolean
|
|
Default value : false
|
|
|
Inherited from
DfBaseComponent
|
|
| isRetailChannel | |
Type : boolean
|
|
|
Inherited from
DfBaseComponent
|
|
| validationConfigs | |
Type : ValidationConfig[] | undefined
|
|
|
Inherited from
DfBaseComponent
|
|
| formEvent | |
Type : DfEventPayload
|
|
|
Inherited from
DfBaseComponent
|
|
|
Emits when events associated to the form control happen. The emitted object contains the data necessary to uniquely identify the event (field id and event type). It also contains the event data. |
|
| onBlur | ||||||
onBlur(event: FocusEvent)
|
||||||
|
Parameters :
Returns :
void
|
| isCheckboxGroup |
Type : unknown
|
Default value : computed(() => this.config().type === 'CHECKBOX_GROUP')
|
| isHorizontal |
Type : unknown
|
Default value : computed(() => !!this.groupLayout()?.horizontal)
|
| componentOrControlInitFinished |
Type : unknown
|
Default value : new ReplaySubject<AbstractControl | undefined>(1)
|
|
Inherited from
DfBaseComponent
|
|
This ReplaySubject is provided to emit the control once it is initialized. |
| errorMessages |
Type : WritableSignal<Observable[]>
|
Default value : signal([])
|
|
Inherited from
DfBaseComponent
|
|
The resolved validation error messages for the current control state. |
| Readonly nxErrorAppearance |
Type : ErrorStyleType
|
Default value : inject(ERROR_DEFAULT_OPTIONS, { optional: true })?.appearance ||
(inject<CHANNEL>(CHANNEL_TOKEN) === CHANNEL.EXPERT ? 'text' : 'message')
|
|
Inherited from
DfBaseComponent
|
import {
CONTAINER_BREAKPOINT_M,
DfBaseComponent,
DfOptions,
DfOptionsProviderService,
FORM_CONTAINER_WIDTH
} from '@allianz/taly-core/dynamic-form';
import { RowJustification } from '@allianz/ng-aquila/grid';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
computed,
DoCheck,
ElementRef,
inject,
input,
OnInit,
Signal
} from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { FormGroupDirective, NgForm, UntypedFormControl } from '@angular/forms';
import { of, switchMap } from 'rxjs';
import { CheckboxLabelSize, DfCheckboxConfig, DfCheckboxGroupConfig } from './checkbox.model';
import { ErrorStateMatcher } from '@allianz/ng-aquila/utils';
@Component({
selector: 'df-checkbox',
styleUrls: ['./checkbox.component.scss'],
templateUrl: './checkbox.component.html',
standalone: false,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DfCheckboxComponent
extends DfBaseComponent<DfCheckboxConfig | DfCheckboxGroupConfig>
implements OnInit, DoCheck
{
private readonly _parentForm = inject(NgForm, { optional: true });
private readonly _parentFormGroup = inject(FormGroupDirective, { optional: true });
private readonly errorStateMatcher = inject(ErrorStateMatcher);
private readonly cdr = inject(ChangeDetectorRef);
private readonly _elementRef = inject(ElementRef);
private optionsProviderService = inject(DfOptionsProviderService, { optional: true });
private formContainerWidth = inject(FORM_CONTAINER_WIDTH, { optional: true });
private groupLayout = computed(() => {
const config = this.config();
return config.type === 'CHECKBOX_GROUP' ? config.layout ?? null : null;
});
private readonly DEFAULT_OPTION_COLUMN_SPAN = 4;
protected errorState = false;
protected readonly checkboxOptions: Signal<DfOptions[]> = toSignal(
toObservable(this.config).pipe(
switchMap((config) => {
if (config.type !== 'CHECKBOX_GROUP') return of([]);
if (Array.isArray(config.options)) return of(config.options);
if (typeof config.options === 'string' && this.optionsProviderService) {
return this.optionsProviderService.getDfOptions(config.options);
}
return of([]);
})
),
{ initialValue: [] }
);
protected horizontalOptionsAlignment = computed(() => this.computeHorizontalOptionsAlignment());
private isGroupLabelLeftAligned = computed(() => {
const layout = this.groupLayout();
return !!(
layout &&
this.isRetailChannel() &&
layout.horizontal !== true &&
layout.groupLabelLeftAlignInRetail
);
});
protected groupLabelCol = computed(() => this.computeGroupLabelCol());
protected labelCenter = computed(() => this.isRetailChannel() && !this.isGroupLabelLeftAligned());
protected optionColumnSpan = computed(() => {
const layout = this.groupLayout();
const columnSpan = (layout && layout.optionsColumnSpan) ?? this.DEFAULT_OPTION_COLUMN_SPAN;
const containerWidth = this.formContainerWidth?.() ?? Infinity;
return containerWidth <= CONTAINER_BREAKPOINT_M ? '12' : `${columnSpan}`;
});
override control = input<UntypedFormControl>(new UntypedFormControl());
isHorizontal = computed(() => !!this.groupLayout()?.horizontal);
isCheckboxGroup = computed(() => this.config().type === 'CHECKBOX_GROUP');
protected labelSize = computed(() =>
this.config().labelSizeSmall ? CheckboxLabelSize.Small : CheckboxLabelSize.Large
);
override ngOnInit() {
super.ngOnInit();
this.emitFormControlEventOnValueChanges();
}
ngDoCheck(): void {
const controlValue = this.control();
if (controlValue) {
// We follow the Aquila approach with the ErrorStateMatcher here:
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
const newErrorState = this.errorStateMatcher.isErrorState(
controlValue,
this._parentFormGroup || this._parentForm
);
if (this.errorState !== newErrorState) {
this.errorState = newErrorState;
this.cdr.markForCheck();
}
}
}
private computeHorizontalOptionsAlignment(): RowJustification {
const layout = this.groupLayout();
if (!layout?.horizontal) return 'start';
const itemsPerRow = Math.floor(
12 / (layout.optionsColumnSpan || this.DEFAULT_OPTION_COLUMN_SPAN)
);
const hasMultipleRows = this.checkboxOptions().length > itemsPerRow;
return this.isRetailChannel() && !hasMultipleRows ? 'center' : 'start';
}
private computeGroupLabelCol(): string {
if (!this.isGroupLabelLeftAligned()) {
return '12';
}
const layout = this.groupLayout();
const columnSpan = layout?.optionsColumnSpan || this.DEFAULT_OPTION_COLUMN_SPAN;
const containerWidth = this.formContainerWidth?.() ?? Infinity;
return containerWidth <= CONTAINER_BREAKPOINT_M ? '12' : `${columnSpan}`;
}
onBlur(event: FocusEvent): void {
const checkboxGroupHasFocus = this._elementRef.nativeElement.contains(event.relatedTarget);
if (!checkboxGroupHasFocus) {
this.emitFormEvent('onBlurEvent', this.control().value);
}
}
}
<!-- Single Checkbox -->
@if (!isCheckboxGroup()) {
<nx-checkbox
[formControl]="control()"
[labelSize]="labelSize()"
[attr.data-testid]="config().testId"
class="nx-margin-0"
(focusout)="emitFormEvent('onBlurEvent', control().value)"
>
@for (message$ of errorMessages(); track $index) {
<nx-error [appearance]="nxErrorAppearance">{{ message$ | async }}</nx-error>
}
<div class="df-checkbox__label-container">
<div class="nx-margin-0">
<span>{{ config().label | interpolateFromStore | async }}</span>
<br />
<span>{{ config().hint | interpolateFromStore | async }}</span>
</div>
@if (config().infoIcon) {
<df-info-icon [config]="config().infoIcon"></df-info-icon>
}
</div>
</nx-checkbox>
} @else {
<!-- Checkbox Group -->
<fieldset nxLayout="grid nopadding" class="df-checkbox-group__container">
<div nxRow [rowJustify]="isRetailChannel() ? 'center' : 'start'">
<div
[nxCol]="groupLabelCol()"
[ngClass]="{ 'text-center': labelCenter() }"
data-testid="groupLabelCol"
>
<nx-label
data-testid="checkboxLabel"
[size]="isRetailChannel() ? 'large' : 'small'"
[ngClass]="{ 'nx-font-weight-regular': isRetailChannel(), 'text-center': labelCenter() }"
>
{{ config().label | interpolateFromStore | async }}@if (config().infoIcon) {
<df-info-icon nxFormfieldAppendix [config]="config().infoIcon"></df-info-icon>
}
</nx-label>
</div>
</div>
<nx-checkbox-group
[formControl]="control()"
[name]="config().id"
[attr.data-testid]="config().testId"
(focusout)="onBlur($event)"
>
@if (isHorizontal()) {
<div nxRow [rowJustify]="horizontalOptionsAlignment()" data-testid="rowInHorizontalLayout">
@for (option of checkboxOptions(); track $index) {
<div [nxCol]="optionColumnSpan()" data-testid="columnInHorizontalLayout">
<nx-checkbox
[value]="option.value.toString()"
[labelSize]="labelSize()"
[attr.data-testid]="option?.testId"
>
<span>{{ option.label | interpolateFromStore | async }}</span>
</nx-checkbox>
</div>
}
</div>
} @else { @for (option of checkboxOptions(); track $index) {
<div
nxRow
[rowJustify]="isRetailChannel() ? 'center' : 'start'"
data-testid="rowInVerticalLayout"
>
<div [nxCol]="optionColumnSpan()" data-testid="columnInVerticalLayout">
<nx-checkbox
[value]="option.value.toString()"
[labelSize]="labelSize()"
[attr.data-testid]="option?.testId"
>
<span>{{ option.label | interpolateFromStore | async }}</span>
</nx-checkbox>
</div>
</div>
} } @for (message$ of errorMessages(); track $index) {
<nx-error [appearance]="nxErrorAppearance">{{ message$ | async }}</nx-error>
}
</nx-checkbox-group>
@if (config().hint) {
<br />
<span>{{ config().hint | interpolateFromStore | async }}</span>
}
</fieldset>
} @if (config().note && !errorState) {
<nx-message context="info">
<span>{{ config().note | interpolateFromStore | async }}</span>
</nx-message>
}
./checkbox.component.scss
:host {
display: block;
}
.df-checkbox__label-container {
display: flex;
gap: 8px;
align-items: center;
justify-content: left;
}
.df-info-icon {
align-self: start;
// Used to compensate the icon top position with the switcher
position: relative;
bottom: 2px;
}
.text-center {
text-align: center;
}
.df-checkbox-group__container {
nx-checkbox {
margin-top: var(--vertical-inner-section-spacing);
margin-bottom: 0;
}
df-info-icon {
display: inline-flex;
align-items: center;
padding-left: 8px;
}
}