File

src/checkbox/checkbox.component.ts

Description

Get started with importing the module:

Example :
import { CheckboxModule } from 'carbon-components-angular';

See demo

Implements

ControlValueAccessor AfterViewInit

Metadata

Index

Properties
Methods
Inputs
Outputs
HostListeners
Accessors

Constructor

constructor(changeDetectorRef: ChangeDetectorRef, hostGroup: CheckboxGroupHost | null)

Creates an instance of Checkbox.

Parameters :
Name Type Optional
changeDetectorRef ChangeDetectorRef No
hostGroup CheckboxGroupHost | null No

Inputs

ariaLabel
Type : string
ariaLabelledby
Type : string
checked
Type : boolean

Sets the checked state. true for checked, false for unchecked

Allows double binding with the checkedChange Output.

decorator
Type : TemplateRef<any>

Optional TemplateRef (e.g. AI label) rendered next to the label text.

disabled
Type : boolean
Default value : false

Set to true for a disabled checkbox.

helperText
Type : string | TemplateRef<any>

Optional helper text displayed below the checkbox label. Not shown when invalid or warn is true.

hideLabel
Type : boolean
Default value : false

Set to true to hide the checkbox labels.

id
Type : string
Default value : `checkbox-${Checkbox.checkboxCount}`

The unique id for the checkbox component.

indeterminate
Type : boolean

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.

invalid
Type : boolean

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.

invalidText
Type : string | TemplateRef<any>

The error message displayed when invalid is true.

name
Type : string

Sets the name attribute on the input element.

readOnly
Type : boolean

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.

required
Type : boolean

Reflects the required attribute of the input element.

skeleton
Type : boolean
Default value : false

Set to true for a loading checkbox.

title
Type : string
Default value : ""

Optional title for the <label> element.

value
Type : CheckboxValue

Sets the value attribute on the input element.

warn
Type : boolean

Set to true to show the checkbox in a warning state. When omitted inside a cds-checkbox-group, the group's warn value applies.

warnText
Type : string | TemplateRef<any>

The warning message displayed when warn is true and invalid is false.

Outputs

checkedChange
Type : EventEmitter

Emits an event when the value of the checkbox changes.

Allows double biding with the checked Input.

click
Type : EventEmitter

Emits click event.

indeterminateChange
Type : EventEmitter

Emits event notifying other classes when a change in state occurs specifically on an indeterminate checkbox.

HostListeners

focusout
focusout()

Methods

emitChangeEvent
emitChangeEvent()

Creates instance of CheckboxChange used to propagate the change event.

Returns : void
focusOut
focusOut()
Decorators :
@HostListener('focusout')
Returns : void
isTemplate
isTemplate(value: any)

Returns true when the provided value is a TemplateRef.

Parameters :
Name Type Optional
value any No
Returns : boolean
markForCheckFromGroup
markForCheckFromGroup()

Invoked by CheckboxGroup when group readOnly, invalid, warn change so OnPush checkboxes still refresh inherited state from CHECKBOX_GROUP_HOST.

Returns : void
ngAfterViewInit
ngAfterViewInit()

Updates the checkbox if it is in the indeterminate state.

Returns : void
onChange
onChange(event: Event)

Executes on the event of a change within Checkbox to block propagation.

Parameters :
Name Type Optional
event Event No
Returns : void
onClick
onClick(event: Event)

Handles click events on the Checkbox and emits changes to other classes.

Parameters :
Name Type Optional
event Event No
Returns : void
Public registerOnChange
registerOnChange(fn: any)

Sets a method in order to propagate changes back to the form.

Parameters :
Name Type Optional
fn any No
Returns : void
Public registerOnTouched
registerOnTouched(fn: any)

Registers a callback to be triggered when the control has been touched.

Parameters :
Name Type Optional Description
fn any No

Callback to be triggered when the checkbox is touched.

Returns : void
Private setChecked
setChecked(checked: boolean, resetIndeterminate: boolean)

Sets checked state and optionally resets indeterminate state.

Parameters :
Name Type Optional
checked boolean No
resetIndeterminate boolean No
Returns : void
setDisabledState
setDisabledState(isDisabled: boolean)

ControlValueAccessor method to programmatically disable the checkbox.

ex: this.formGroup.get("myCheckbox").disable();

Parameters :
Name Type Optional Description
isDisabled boolean No

true to disable the checkbox

Returns : void
Public toggle
toggle()

Toggle the selected state of the checkbox.

Returns : void
transitionCheckboxState
transitionCheckboxState(newState: CheckboxState)

Handles changes between checkbox states.

Parameters :
Name Type Optional
newState CheckboxState No
Returns : void
Public writeValue
writeValue(value: any)

Writes a value from ngModel to the component.

In this case the value is the checked property.

Parameters :
Name Type Optional Description
value any No

boolean, corresponds to the checked property.

Returns : void

Properties

_checked
Default value : false

Set to true if the input checkbox is selected (or checked).

_indeterminate
Default value : false

Set to true if the input checkbox is in state indeterminate.

Static checkboxCount
Type : number
Default value : 0

Variable used for creating unique ids for checkbox components.

currentCheckboxState
Default value : CheckboxState.Init

Keeps a reference to the checkboxes current state, as defined in CheckboxState.

Readonly helperId
Default value : `checkbox-helper-${Checkbox.helperIdCounter++}`
Private Static helperIdCounter
Type : number
Default value : 0
inputCheckbox
Type : ElementRef
Decorators :
@ViewChild('inputCheckbox')

Maintains a reference to the view DOM element of the Checkbox.

onTouched
Type : function
Default value : () => {...}

Called when checkbox is blurred. Needed to properly implement ControlValueAccessor.

propagateChange
Default value : () => {...}

Method set in registerOnChange to propagate changes back to the form.

Accessors

indeterminate
getindeterminate()

Reflects whether the checkbox state is indeterminate.

setindeterminate(indeterminate: boolean)

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.

Parameters :
Name Type Optional
indeterminate boolean No
Returns : void
checked
getchecked()

Returns value true if state is selected for the checkbox.

setchecked(checked: boolean)

Sets the checked state. true for checked, false for unchecked

Allows double binding with the checkedChange Output.

Parameters :
Name Type Optional
checked boolean No
Returns : void
effectiveReadOnly
geteffectiveReadOnly()
effectiveInvalid
geteffectiveInvalid()
effectiveWarn
geteffectiveWarn()
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();
	}
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""