src/checkbox/checkbox.component.ts
Get started with importing the module:
Example :import { CheckboxModule } from 'carbon-components-angular';
ControlValueAccessor
AfterViewInit
| changeDetection | ChangeDetectionStrategy.OnPush |
| providers |
{
provide: NG_VALUE_ACCESSOR, useExisting: Checkbox, multi: true
}
|
| selector | cds-checkbox, ibm-checkbox |
| template | |
Properties |
|
Methods |
|
Inputs |
Outputs |
HostListeners |
Accessors |
constructor(changeDetectorRef: ChangeDetectorRef, hostGroup: CheckboxGroupHost | null)
|
|||||||||
|
Defined in src/checkbox/checkbox.component.ts:292
|
|||||||||
|
Creates an instance of
Parameters :
|
| ariaLabel | |
Type : string
|
|
|
Defined in src/checkbox/checkbox.component.ts:160
|
|
| ariaLabelledby | |
Type : string
|
|
|
Defined in src/checkbox/checkbox.component.ts:161
|
|
| checked | |
Type : boolean
|
|
|
Defined in src/checkbox/checkbox.component.ts:244
|
|
|
Sets the Allows double binding with the |
|
| decorator | |
Type : TemplateRef<any>
|
|
|
Defined in src/checkbox/checkbox.component.ts:205
|
|
|
Optional |
|
| disabled | |
Type : boolean
|
|
Default value : false
|
|
|
Defined in src/checkbox/checkbox.component.ts:135
|
|
|
Set to |
|
| helperText | |
Type : string | TemplateRef<any>
|
|
|
Defined in src/checkbox/checkbox.component.ts:172
|
|
|
Optional helper text displayed below the checkbox label.
Not shown when |
|
| hideLabel | |
Type : boolean
|
|
Default value : false
|
|
|
Defined in src/checkbox/checkbox.component.ts:143
|
|
|
Set to |
|
| id | |
Type : string
|
|
Default value : `checkbox-${Checkbox.checkboxCount}`
|
|
|
Defined in src/checkbox/checkbox.component.ts:151
|
|
|
The unique id for the checkbox component. |
|
| indeterminate | |
Type : boolean
|
|
|
Defined in src/checkbox/checkbox.component.ts:212
|
|
|
Set the checkbox's indeterminate state to match the parameter and transition the view to reflect the change. Allows double binding with the |
|
| invalid | |
Type : boolean
|
|
|
Defined in src/checkbox/checkbox.component.ts:178
|
|
|
Set to |
|
| invalidText | |
Type : string | TemplateRef<any>
|
|
|
Defined in src/checkbox/checkbox.component.ts:183
|
|
|
The error message displayed when |
|
| name | |
Type : string
|
|
|
Defined in src/checkbox/checkbox.component.ts:147
|
|
|
Sets the name attribute on the |
|
| readOnly | |
Type : boolean
|
|
|
Defined in src/checkbox/checkbox.component.ts:200
|
|
|
When |
|
| required | |
Type : boolean
|
|
|
Defined in src/checkbox/checkbox.component.ts:155
|
|
|
Reflects the required attribute of the |
|
| skeleton | |
Type : boolean
|
|
Default value : false
|
|
|
Defined in src/checkbox/checkbox.component.ts:139
|
|
|
Set to |
|
| title | |
Type : string
|
|
Default value : ""
|
|
|
Defined in src/checkbox/checkbox.component.ts:166
|
|
|
Optional title for the |
|
| value | |
Type : CheckboxValue
|
|
|
Defined in src/checkbox/checkbox.component.ts:159
|
|
|
Sets the value attribute on the |
|
| warn | |
Type : boolean
|
|
|
Defined in src/checkbox/checkbox.component.ts:189
|
|
|
Set to |
|
| warnText | |
Type : string | TemplateRef<any>
|
|
|
Defined in src/checkbox/checkbox.component.ts:194
|
|
|
The warning message displayed when |
|
| checkedChange | |
Type : EventEmitter
|
|
|
Defined in src/checkbox/checkbox.component.ts:265
|
|
|
Emits an event when the value of the checkbox changes. Allows double biding with the |
|
| click | |
Type : EventEmitter
|
|
|
Defined in src/checkbox/checkbox.component.ts:258
|
|
|
Emits click event. |
|
| indeterminateChange | |
Type : EventEmitter
|
|
|
Defined in src/checkbox/checkbox.component.ts:271
|
|
|
Emits event notifying other classes when a change in state occurs specifically on an indeterminate checkbox. |
|
| focusout |
focusout()
|
|
Defined in src/checkbox/checkbox.component.ts:381
|
| emitChangeEvent |
emitChangeEvent()
|
|
Defined in src/checkbox/checkbox.component.ts:433
|
|
Creates instance of
Returns :
void
|
| focusOut |
focusOut()
|
Decorators :
@HostListener('focusout')
|
|
Defined in src/checkbox/checkbox.component.ts:381
|
|
Returns :
void
|
| isTemplate | ||||||
isTemplate(value: any)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:455
|
||||||
|
Returns
Parameters :
Returns :
boolean
|
| markForCheckFromGroup |
markForCheckFromGroup()
|
|
Defined in src/checkbox/checkbox.component.ts:376
|
|
Invoked by
Returns :
void
|
| ngAfterViewInit |
ngAfterViewInit()
|
|
Defined in src/checkbox/checkbox.component.ts:441
|
|
Updates the checkbox if it is in the indeterminate state.
Returns :
void
|
| onChange | ||||||
onChange(event: Event)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:388
|
||||||
|
Executes on the event of a change within
Parameters :
Returns :
void
|
| onClick | ||||||
onClick(event: Event)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:395
|
||||||
|
Handles click events on the
Parameters :
Returns :
void
|
| Public registerOnChange | ||||||
registerOnChange(fn: any)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:348
|
||||||
|
Sets a method in order to propagate changes back to the form.
Parameters :
Returns :
void
|
| Public registerOnTouched | ||||||||
registerOnTouched(fn: any)
|
||||||||
|
Defined in src/checkbox/checkbox.component.ts:356
|
||||||||
|
Registers a callback to be triggered when the control has been touched.
Parameters :
Returns :
void
|
| Private setChecked |
setChecked(checked: boolean, resetIndeterminate: boolean)
|
|
Defined in src/checkbox/checkbox.component.ts:462
|
|
Sets checked state and optionally resets indeterminate state.
Returns :
void
|
| setDisabledState | ||||||||
setDisabledState(isDisabled: boolean)
|
||||||||
|
Defined in src/checkbox/checkbox.component.ts:367
|
||||||||
|
ex:
Parameters :
Returns :
void
|
| Public toggle |
toggle()
|
|
Defined in src/checkbox/checkbox.component.ts:325
|
|
Toggle the selected state of the checkbox.
Returns :
void
|
| transitionCheckboxState | ||||||
transitionCheckboxState(newState: CheckboxState)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:426
|
||||||
|
Handles changes between checkbox states.
Parameters :
Returns :
void
|
| Public writeValue | ||||||||
writeValue(value: any)
|
||||||||
|
Defined in src/checkbox/checkbox.component.ts:340
|
||||||||
|
Writes a value from In this case the value is the
Parameters :
Returns :
void
|
| _checked |
Default value : false
|
|
Defined in src/checkbox/checkbox.component.ts:276
|
|
Set to |
| _indeterminate |
Default value : false
|
|
Defined in src/checkbox/checkbox.component.ts:280
|
|
Set to |
| Static checkboxCount |
Type : number
|
Default value : 0
|
|
Defined in src/checkbox/checkbox.component.ts:128
|
|
Variable used for creating unique ids for checkbox components. |
| currentCheckboxState |
Default value : CheckboxState.Init
|
|
Defined in src/checkbox/checkbox.component.ts:285
|
|
Keeps a reference to the checkboxes current state, as defined in |
| Readonly helperId |
Default value : `checkbox-helper-${Checkbox.helperIdCounter++}`
|
|
Defined in src/checkbox/checkbox.component.ts:292
|
| Private Static helperIdCounter |
Type : number
|
Default value : 0
|
|
Defined in src/checkbox/checkbox.component.ts:130
|
| inputCheckbox |
Type : ElementRef
|
Decorators :
@ViewChild('inputCheckbox')
|
|
Defined in src/checkbox/checkbox.component.ts:290
|
|
Maintains a reference to the view DOM element of the |
| onTouched |
Type : function
|
Default value : () => {...}
|
|
Defined in src/checkbox/checkbox.component.ts:421
|
|
Called when checkbox is blurred. Needed to properly implement |
| propagateChange |
Default value : () => {...}
|
|
Defined in src/checkbox/checkbox.component.ts:450
|
|
Method set in |
| indeterminate | ||||||
getindeterminate()
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:235
|
||||||
|
Reflects whether the checkbox state is indeterminate. |
||||||
setindeterminate(indeterminate: boolean)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:212
|
||||||
|
Set the checkbox's indeterminate state to match the parameter and transition the view to reflect the change. Allows double binding with the
Parameters :
Returns :
void
|
| checked | ||||||
getchecked()
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:251
|
||||||
|
Returns value |
||||||
setchecked(checked: boolean)
|
||||||
|
Defined in src/checkbox/checkbox.component.ts:244
|
||||||
|
Sets the Allows double binding with the
Parameters :
Returns :
void
|
| effectiveReadOnly |
geteffectiveReadOnly()
|
|
Defined in src/checkbox/checkbox.component.ts:304
|
| effectiveInvalid |
geteffectiveInvalid()
|
|
Defined in src/checkbox/checkbox.component.ts:310
|
| effectiveWarn |
geteffectiveWarn()
|
|
Defined in src/checkbox/checkbox.component.ts:316
|
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
Optional,
Output,
TemplateRef,
ViewChild,
HostListener
} from "@angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms";
import { CheckboxValue } from "./checkbox.types";
import { CHECKBOX_GROUP_HOST, CheckboxGroupHost } from "./checkbox-group-host";
/**
* Defines the set of states for a checkbox component.
*/
export enum CheckboxState {
Init,
Indeterminate,
Checked,
Unchecked
}
/**
* Get started with importing the module:
*
* ```typescript
* import { CheckboxModule } from 'carbon-components-angular';
* ```
*
* [See demo](../../?path=/story/components-checkbox--basic)
*/
@Component({
selector: "cds-checkbox, ibm-checkbox",
template: `
<div class="cds--form-item cds--checkbox-wrapper"
[ngClass]="{
'cds--checkbox-wrapper--invalid': !effectiveReadOnly && effectiveInvalid,
'cds--checkbox-wrapper--warning': !effectiveReadOnly && !effectiveInvalid && effectiveWarn,
'cds--checkbox-wrapper--readonly': effectiveReadOnly,
'cds--checkbox-wrapper--decorator': !!decorator
}">
<input
#inputCheckbox
class="cds--checkbox"
type="checkbox"
[id]="id + '_input'"
[value]="value"
[name]="name"
[required]="required"
[checked]="checked"
[disabled]="disabled"
[attr.data-invalid]="(!effectiveReadOnly && effectiveInvalid) ? true : null"
[attr.aria-readonly]="effectiveReadOnly ? true : null"
[attr.aria-labelledby]="ariaLabelledby"
[attr.aria-describedby]="(helperText && !effectiveInvalid && !effectiveWarn) ? helperId : null"
(change)="onChange($event)"
(click)="onClick($event)">
<label
[for]="id + '_input'"
[attr.aria-label]="ariaLabel"
[attr.title]="title || null"
class="cds--checkbox-label"
[ngClass]="{
'cds--skeleton' : skeleton
}">
<span [ngClass]="{'cds--visually-hidden' : hideLabel}" class="cds--checkbox-label-text">
<ng-content></ng-content>
<ng-container *ngIf="decorator">
<div class="cds--checkbox-wrapper-inner--decorator">
<ng-template [ngTemplateOutlet]="decorator"></ng-template>
</div>
</ng-container>
</span>
</label>
<div class="cds--checkbox__validation-msg">
<ng-container *ngIf="!effectiveReadOnly && effectiveInvalid">
<svg
cdsIcon="warning--filled"
size="16"
class="cds--checkbox__invalid-icon">
</svg>
<div class="cds--form-requirement">
<ng-container *ngIf="!isTemplate(invalidText)">{{invalidText}}</ng-container>
<ng-template *ngIf="isTemplate(invalidText)" [ngTemplateOutlet]="$any(invalidText)"></ng-template>
</div>
</ng-container>
<ng-container *ngIf="!effectiveReadOnly && !effectiveInvalid && effectiveWarn">
<svg
cdsIcon="warning--alt--filled"
size="16"
class="cds--checkbox__invalid-icon cds--checkbox__invalid-icon--warning">
</svg>
<div class="cds--form-requirement">
<ng-container *ngIf="!isTemplate(warnText)">{{warnText}}</ng-container>
<ng-template *ngIf="isTemplate(warnText)" [ngTemplateOutlet]="$any(warnText)"></ng-template>
</div>
</ng-container>
</div>
<div
*ngIf="helperText && !effectiveInvalid && !effectiveWarn"
class="cds--form__helper-text"
[id]="helperId">
<ng-container *ngIf="!isTemplate(helperText)">{{helperText}}</ng-container>
<ng-template *ngIf="isTemplate(helperText)" [ngTemplateOutlet]="$any(helperText)"></ng-template>
</div>
</div>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: Checkbox,
multi: true
}
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Checkbox implements ControlValueAccessor, AfterViewInit {
/**
* Variable used for creating unique ids for checkbox components.
*/
static checkboxCount = 0;
private static helperIdCounter = 0;
/**
* Set to `true` for a disabled checkbox.
*/
@Input() disabled = false;
/**
* Set to `true` for a loading checkbox.
*/
@Input() skeleton = false;
/**
* Set to `true` to hide the checkbox labels.
*/
@Input() hideLabel = false;
/**
* Sets the name attribute on the `input` element.
*/
@Input() name: string;
/**
* The unique id for the checkbox component.
*/
@Input() id = `checkbox-${Checkbox.checkboxCount}`;
/**
* Reflects the required attribute of the `input` element.
*/
@Input() required: boolean;
/**
* Sets the value attribute on the `input` element.
*/
@Input() value: CheckboxValue;
@Input() ariaLabel: string;
@Input() ariaLabelledby: string;
/**
* Optional title for the `<label>` element.
*/
@Input() title = "";
/**
* Optional helper text displayed below the checkbox label.
* Not shown when `invalid` or `warn` is `true`.
*/
@Input() helperText: string | TemplateRef<any>;
/**
* Set to `true` to show the checkbox in an invalid/error state.
* When omitted inside a `cds-checkbox-group`, the group's `invalid` value applies.
*/
@Input() invalid?: boolean;
/**
* The error message displayed when `invalid` is `true`.
*/
@Input() invalidText: string | TemplateRef<any>;
/**
* Set to `true` to show the checkbox in a warning state.
* When omitted inside a `cds-checkbox-group`, the group's `warn` value applies.
*/
@Input() warn?: boolean;
/**
* The warning message displayed when `warn` is `true` and `invalid` is `false`.
*/
@Input() warnText: string | TemplateRef<any>;
/**
* When `true`, the checkbox cannot be toggled (matches `readonly` attribute semantics for form controls).
* When omitted inside a `cds-checkbox-group`, the group's `readOnly` value applies.
*/
@Input() readOnly?: boolean;
/**
* Optional `TemplateRef` (e.g. AI label) rendered next to the label text.
*/
@Input() decorator: TemplateRef<any>;
/**
* Set the checkbox's indeterminate state to match the parameter and transition the view to reflect the change.
*
* Allows double binding with the `indeterminateChange` Output.
*/
@Input() set indeterminate(indeterminate: boolean) {
if (indeterminate === this._indeterminate) {
return;
}
this._indeterminate = indeterminate;
if (this._indeterminate) {
this.transitionCheckboxState(CheckboxState.Indeterminate);
} else {
this.transitionCheckboxState(this.checked ? CheckboxState.Checked : CheckboxState.Unchecked);
}
if (this.inputCheckbox && this.inputCheckbox.nativeElement) {
this.inputCheckbox.nativeElement.indeterminate = indeterminate;
}
this.changeDetectorRef.markForCheck();
this.indeterminateChange.emit(this._indeterminate);
}
/**
* Reflects whether the checkbox state is indeterminate.
*/
get indeterminate() {
return this._indeterminate;
}
/**
* Sets the `checked` state. `true` for checked, `false` for unchecked
*
* Allows double binding with the `checkedChange` Output.
*/
@Input() set checked (checked: boolean) {
this.setChecked(checked, false);
}
/**
* Returns value `true` if state is selected for the checkbox.
*/
get checked() {
return this._checked;
}
/**
* Emits click event.
*/
@Output() click = new EventEmitter<void>();
/**
* Emits an event when the value of the checkbox changes.
*
* Allows double biding with the `checked` Input.
*/
@Output() checkedChange = new EventEmitter<boolean>();
/**
* Emits event notifying other classes when a change in state occurs specifically
* on an indeterminate checkbox.
*/
@Output() indeterminateChange = new EventEmitter<boolean>();
/**
* Set to `true` if the input checkbox is selected (or checked).
*/
_checked = false;
/**
* Set to `true` if the input checkbox is in state indeterminate.
*/
_indeterminate = false;
/**
* Keeps a reference to the checkboxes current state, as defined in `CheckboxState`.
*/
currentCheckboxState = CheckboxState.Init;
/**
* Maintains a reference to the view DOM element of the `Checkbox`.
*/
@ViewChild("inputCheckbox") inputCheckbox: ElementRef;
readonly helperId = `checkbox-helper-${Checkbox.helperIdCounter++}`;
/**
* Creates an instance of `Checkbox`.
*/
constructor(
protected changeDetectorRef: ChangeDetectorRef,
@Optional() @Inject(CHECKBOX_GROUP_HOST) private hostGroup: CheckboxGroupHost | null
) {
Checkbox.checkboxCount++;
}
get effectiveReadOnly(): boolean {
const own = this.readOnly;
const group = this.hostGroup?.readOnly ?? false;
return !!(own !== undefined ? own : group);
}
get effectiveInvalid(): boolean {
const own = this.invalid;
const group = this.hostGroup?.invalid ?? false;
return !!(own !== undefined ? own : group);
}
get effectiveWarn(): boolean {
const own = this.warn;
const group = this.hostGroup?.warn ?? false;
return !!(own !== undefined ? own : group);
}
/**
* Toggle the selected state of the checkbox.
*/
public toggle() {
if (this.effectiveReadOnly) {
return;
}
// Flip checked and reset indeterminate
this.setChecked(!this.checked, true);
}
/**
* Writes a value from `ngModel` to the component.
*
* In this case the value is the `checked` property.
*
* @param value boolean, corresponds to the `checked` property.
*/
public writeValue(value: any) {
// Set checked and reset indeterminate
this.setChecked(!!value, true);
}
/**
* Sets a method in order to propagate changes back to the form.
*/
public registerOnChange(fn: any) {
this.propagateChange = fn;
}
/**
* Registers a callback to be triggered when the control has been touched.
* @param fn Callback to be triggered when the checkbox is touched.
*/
public registerOnTouched(fn: any) {
this.onTouched = fn;
}
/**
* `ControlValueAccessor` method to programmatically disable the checkbox.
*
* ex: `this.formGroup.get("myCheckbox").disable();`
*
* @param isDisabled `true` to disable the checkbox
*/
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
this.changeDetectorRef.markForCheck();
}
/**
* Invoked by `CheckboxGroup` when group `readOnly`, `invalid`, `warn` change so `OnPush`
* checkboxes still refresh inherited state from `CHECKBOX_GROUP_HOST`.
*/
markForCheckFromGroup(): void {
this.changeDetectorRef.markForCheck();
}
@HostListener("focusout")
focusOut() {
this.onTouched();
}
/**
* Executes on the event of a change within `Checkbox` to block propagation.
*/
onChange(event: Event) {
event.stopPropagation();
}
/**
* Handles click events on the `Checkbox` and emits changes to other classes.
*/
onClick(event: Event) {
if (this.effectiveReadOnly) {
event.preventDefault();
if (this.click.observers.length) {
this.click.emit();
}
return;
}
if (this.click.observers.length) {
// Disable default checkbox activation behavior which flips checked and resets indeterminate.
// This allows the parent component to control the checked/indeterminate properties.
event.preventDefault();
this.click.emit();
return;
}
if (!this.disabled) {
this.toggle();
this.transitionCheckboxState(this._checked ? CheckboxState.Checked : CheckboxState.Unchecked);
this.emitChangeEvent();
}
}
/**
* Called when checkbox is blurred. Needed to properly implement `ControlValueAccessor`.
*/
onTouched: () => any = () => {};
/**
* Handles changes between checkbox states.
*/
transitionCheckboxState(newState: CheckboxState) {
this.currentCheckboxState = newState;
}
/**
* Creates instance of `CheckboxChange` used to propagate the change event.
*/
emitChangeEvent() {
this.checkedChange.emit(this.checked);
this.propagateChange(this.checked);
}
/**
* Updates the checkbox if it is in the indeterminate state.
*/
ngAfterViewInit() {
if (this.indeterminate && this.inputCheckbox && this.inputCheckbox.nativeElement) {
this.inputCheckbox.nativeElement.indeterminate = true;
}
}
/**
* Method set in `registerOnChange` to propagate changes back to the form.
*/
propagateChange = (_: any) => {};
/**
* Returns `true` when the provided value is a `TemplateRef`.
*/
isTemplate(value: any): boolean {
return value instanceof TemplateRef;
}
/**
* Sets checked state and optionally resets indeterminate state.
*/
private setChecked(checked: boolean, resetIndeterminate: boolean) {
if (checked === this._checked) {
return;
}
this._checked = checked;
// Reset indeterminate if requested
if (resetIndeterminate && this._indeterminate) {
this._indeterminate = false;
Promise.resolve().then(() => {
this.indeterminateChange.emit(this._indeterminate);
});
}
this.changeDetectorRef.markForCheck();
}
}