Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(components/forms): add form errors to checkbox #1994

Merged
merged 6 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,12 @@
</li>
</ul>
</div>
<div>
<sky-checkbox
formControlName="terms"
[required]="true"
labelText="I agree to the terms and conditions"
/>
</div>
<button class="sky-btn sky-btn-primary" type="submit">Submit</button>
</form>
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ export class DemoComponent {
email: new FormControl(false),
phone: new FormControl(false),
text: new FormControl(false),
terms: new FormControl(false),
});
}

protected onSubmit(): void {
this.formGroup.markAllAsTouched();

console.log(this.formGroup.value);
}
}
2 changes: 2 additions & 0 deletions apps/e2e/forms-storybook-e2e/src/e2e/checkbox.component.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ describe('forms-storybook - checkbox', () => {
cy.get('app-checkbox')
.should('exist')
.should('be.visible')
.get('#touched-required-checkbox')
.dblclick()
.get('#standard-checkboxes')
.should('exist')
.should('be.visible')
Expand Down
11 changes: 11 additions & 0 deletions apps/e2e/forms-storybook/src/app/checkbox/checkbox.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@
</sky-checkbox>
</sky-column>
</sky-row>
<sky-row class="sky-padding-even-md">
<sky-column>
<sky-checkbox
ngModel
[checked]="false"
[required]="true"
labelText="Required Checkbox"
id="touched-required-checkbox"
/>
</sky-column>
</sky-row>
<sky-row class="sky-padding-even-md">
<sky-column>
<sky-checkbox [checked]="false" [disabled]="true">
Expand Down
2 changes: 2 additions & 0 deletions apps/e2e/forms-storybook/src/app/checkbox/checkbox.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { SkyCheckboxModule } from '@skyux/forms';
import { SkyHelpInlineModule } from '@skyux/indicators';
Expand All @@ -13,6 +14,7 @@ const routes: Routes = [{ path: '', component: CheckboxComponent }];
declarations: [CheckboxComponent],
imports: [
CommonModule,
FormsModule,
SkyCheckboxModule,
SkyFluidGridModule,
SkyHelpInlineModule,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import {
FormControl,
UntypedFormBuilder,
UntypedFormGroup,
} from '@angular/forms';

@Component({
selector: 'app-checkbox',
Expand Down Expand Up @@ -28,7 +32,7 @@ export class CheckboxComponent implements OnInit {

public ngOnInit(): void {
this.reactiveFormGroup = this.#formBuilder.group({
reactiveCheckbox: [undefined],
reactiveCheckbox: new FormControl(undefined),
});
}

Expand Down
4 changes: 4 additions & 0 deletions libs/components/forms/src/assets/locales/resources_en_US.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,9 @@
"skyux_input_box_help_inline_aria_label": {
"_description": "The accessible label for an input box help inline button",
"message": "Show help content for {0}"
},
"skyux_checkbox_required_label_text": {
"_description": "The label text portion of the required validation message",
"message": "This selection"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
[attr.aria-label]="label"
[attr.aria-labelledby]="labelledBy"
[attr.aria-required]="required ? true : null"
[attr.aria-invalid]="!!ngControl?.errors"
[attr.aria-errormessage]="
labelText && ngControl?.errors ? errorId : undefined
"
(blur)="onInputBlur()"
(change)="onInteractionEvent($event)"
#inputEl
Expand Down Expand Up @@ -58,3 +62,13 @@
<ng-content select="sky-checkbox-label" />
</ng-template>
</label>
<div *ngIf="labelText && ngControl?.errors">
<sky-form-errors
[id]="errorId"
[errors]="ngControl?.errors"
[labelText]="'skyux_checkbox_required_label_text' | skyLibResources"
[showErrors]="ngControl?.touched || ngControl?.dirty"
>
<ng-content select="sky-form-error" />
</sky-form-errors>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { SkyIdService, SkyLogService } from '@skyux/core';

import { BehaviorSubject, Observable } from 'rxjs';

import { SKY_FORM_ERRORS_ENABLED } from '../form-error/form-errors-enabled-token';
import { SkyFormsUtility } from '../shared/forms-utility';

import { SkyCheckboxChange } from './checkbox-change';
Expand All @@ -26,6 +27,7 @@ import { SkyCheckboxChange } from './checkbox-change';
selector: 'sky-checkbox',
templateUrl: './checkbox.component.html',
styleUrls: ['./checkbox.component.scss'],
providers: [{ provide: SKY_FORM_ERRORS_ENABLED, useValue: true }],
})
export class SkyCheckboxComponent implements ControlValueAccessor, OnInit {
/**
Expand Down Expand Up @@ -260,13 +262,19 @@ export class SkyCheckboxComponent implements ControlValueAccessor, OnInit {
#_required = false;

#changeDetector = inject(ChangeDetectorRef);
#defaultId = inject(SkyIdService).generateId();
#idSvc = inject(SkyIdService);
#defaultId = this.#idSvc.generateId();
#logger = inject(SkyLogService);
#ngControl = inject(NgControl, { optional: true, self: true });

protected readonly ngControl = inject(NgControl, {
optional: true,
self: true,
});
public readonly errorId = this.#idSvc.generateId();

constructor() {
if (this.#ngControl) {
this.#ngControl.valueAccessor = this;
if (this.ngControl) {
this.ngControl.valueAccessor = this;
}

this.#checkedChange = new BehaviorSubject<boolean>(this.checked);
Expand All @@ -282,10 +290,10 @@ export class SkyCheckboxComponent implements ControlValueAccessor, OnInit {
}

public ngOnInit(): void {
if (this.#ngControl) {
if (this.ngControl) {
// Backwards compatibility support for anyone still using Validators.Required.
this.required =
this.required || SkyFormsUtility.hasRequiredValidation(this.#ngControl);
this.required || SkyFormsUtility.hasRequiredValidation(this.ngControl);
}
}

Expand Down Expand Up @@ -361,16 +369,16 @@ export class SkyCheckboxComponent implements ControlValueAccessor, OnInit {
#setValidators(): void {
if (
this.required &&
!this.#ngControl?.control?.hasValidator(Validators.requiredTrue)
!this.ngControl?.control?.hasValidator(Validators.requiredTrue)
) {
this.#ngControl?.control?.addValidators(Validators.requiredTrue);
this.#ngControl?.control?.updateValueAndValidity();
this.ngControl?.control?.addValidators(Validators.requiredTrue);
this.ngControl?.control?.updateValueAndValidity();
} else if (
!this.required &&
this.#ngControl?.control?.hasValidator(Validators.requiredTrue)
this.ngControl?.control?.hasValidator(Validators.requiredTrue)
) {
this.#ngControl.control.removeValidators(Validators.requiredTrue);
this.#ngControl.control?.updateValueAndValidity();
this.ngControl.control.removeValidators(Validators.requiredTrue);
this.ngControl.control?.updateValueAndValidity();
}
}
}
20 changes: 18 additions & 2 deletions libs/components/forms/src/lib/modules/checkbox/checkbox.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,28 @@ import { FormsModule } from '@angular/forms';
import { SkyTrimModule } from '@skyux/core';
import { SkyIconModule } from '@skyux/indicators';

import { SkyFormErrorModule } from '../form-error/form-error.module';
import { SkyFormErrorsModule } from '../form-error/form-errors.module';
import { SkyFormsResourcesModule } from '../shared/sky-forms-resources.module';

import { SkyCheckboxLabelComponent } from './checkbox-label.component';
import { SkyCheckboxComponent } from './checkbox.component';

@NgModule({
declarations: [SkyCheckboxComponent, SkyCheckboxLabelComponent],
imports: [CommonModule, FormsModule, SkyIconModule, SkyTrimModule],
exports: [SkyCheckboxComponent, SkyCheckboxLabelComponent],
imports: [
CommonModule,
FormsModule,
SkyFormErrorModule,
SkyFormErrorsModule,
SkyFormsResourcesModule,
SkyIconModule,
SkyTrimModule,
],
exports: [
SkyCheckboxComponent,
SkyCheckboxLabelComponent,
SkyFormErrorModule,
],
})
export class SkyCheckboxModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ const RESOURCES: { [locale: string]: SkyLibResources } = {
skyux_input_box_help_inline_aria_label: {
message: 'Show help content for {0}',
},
skyux_checkbox_required_label_text: { message: 'This selection' },
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ describe('Checkbox harness', () => {
await expectAsync(checkboxHarness.getLabelText()).toBeResolvedTo(undefined);
});

it('should get the label when specified via labelText input', async () => {
const { checkboxHarness } = await setupTest({
dataSkyId: 'my-phone-checkbox',
hideEmailLabel: true,
});

await expectAsync(checkboxHarness.getLabelText()).toBeResolvedTo('Phone');
});

it('should get the checkbox name and value', async () => {
const { checkboxHarness } = await setupTest({
dataSkyId: 'my-email-checkbox',
Expand All @@ -131,4 +140,39 @@ describe('Checkbox harness', () => {
'Could not toggle the checkbox because it is disabled.',
);
});

it('should display a required error message when there is an error', async () => {
const { checkboxHarness } = await setupTest({
dataSkyId: 'my-phone-checkbox',
});

await checkboxHarness.check();
await checkboxHarness.uncheck();

await expectAsync(checkboxHarness.hasRequiredError()).toBeResolvedTo(true);
});

it('should display a custom error message when there is a custom validation error', async () => {
const { checkboxHarness } = await setupTest({
dataSkyId: 'my-mail-checkbox',
});

await checkboxHarness.check();
await checkboxHarness.uncheck();
await checkboxHarness.check();

await expectAsync(
checkboxHarness.hasCustomError('requiredFalse'),
).toBeResolvedTo(true);
});

it('should throw an error if no form error is found', async () => {
const { checkboxHarness } = await setupTest({
dataSkyId: 'my-email-checkbox',
});

await expectAsync(checkboxHarness.hasRequiredError()).toBeRejectedWithError(
'No error found',
);
});
});
20 changes: 20 additions & 0 deletions libs/components/forms/testing/src/checkbox/checkbox-harness.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { HarnessPredicate } from '@angular/cdk/testing';
import { SkyComponentHarness } from '@skyux/core/testing';

import { SkyFormErrorsHarness } from '../public-api';

import { SkyCheckboxHarnessFilters } from './checkbox-harness-filters';
import { SkyCheckboxLabelHarness } from './checkbox-label-harness';

Expand All @@ -18,6 +20,16 @@ export class SkyCheckboxHarness extends SkyComponentHarness {

#getLabel = this.locatorForOptional(SkyCheckboxLabelHarness);

async #getFormErrors(): Promise<SkyFormErrorsHarness> {
const harness = await this.locatorForOptional(SkyFormErrorsHarness)();

if (harness) {
return harness;
}

throw Error('No error found');
}

/**
* Gets a `HarnessPredicate` that can be used to search for a
* `SkyCheckboxHarness` that meets certain criteria.
Expand Down Expand Up @@ -129,6 +141,14 @@ export class SkyCheckboxHarness extends SkyComponentHarness {
}
}

public async hasRequiredError(): Promise<boolean> {
return (await this.#getFormErrors()).hasError('required');
}

public async hasCustomError(errorName: string): Promise<boolean> {
return (await this.#getFormErrors()).hasError(errorName);
}

async #toggle(): Promise<void> {
if (await this.isDisabled()) {
throw new Error('Could not toggle the checkbox because it is disabled.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,25 @@
</li>
<li>
<sky-checkbox
[required]="true"
data-sky-id="my-phone-checkbox"
formControlName="phone"
label="Your phone number"
labelledBy="foo-phone-id"
labelText="Phone"
/>
</li>
<li>
<sky-checkbox
data-sky-id="my-mail-checkbox"
formControlName="mail"
labelText="Mail"
>
<sky-checkbox-label> Phone </sky-checkbox-label>
<sky-form-error
*ngIf="mailControl.errors?.['requiredFalse']"
errorName="requiredFalse"
errorText="This checkbox must be unchecked."
/>
</sky-checkbox>
</li>
</ul>
Expand Down
Loading
Loading