Switch directive toolkit that offers a seamless and accessible solution for creating toggle switches.
Installation
Add and import the module into your imports section.
Module
Standalone directives
Anatomy
Directive's set structure.
Input props
SwitchRoot Attribute Directive
The root directive that contains the switch components. Handles the state and bindings.
Input | Default | Type | Description |
---|---|---|---|
checked | false | model<boolean> | The checked state of the switch. Use two-way binding with [(checked)]. |
disabled | false | boolean | Whether or not the switch is disabled. |
required | false | boolean | Whether or not the switch is required. |
name | random-id | string | The name of the switch. If not provided, a random ID is generated. |
value | on | string | The value of the switch when it is checked. |
Attribute | Value |
---|---|
data-state | "checked" | "unchecked" |
data-disabled | "true" or null |
aria-checked | true when checked |
aria-required | true when required |
role | switch |
SwitchThumb Attribute Directive
The visual indicator that shows the current state of the switch.
Attribute | Value |
---|---|
data-state | "checked" | "unchecked" |
data-disabled | "true" or null |
SwitchInput Structural Directive
A directive that creates a hidden input for form integration. It should be used with an ng-template containing an input element.
Access directive API with exportAS
We can access the state of the switch using a template variable. All the directives expose themselves with the same name. We have access to the directive's attributes and state.
Example
Using the template variable to display the current state of the switch.
Accessibility
This Switch set of directives is designed in accordance with the WAI-ARIA Authoring Practices Guide. This ensures our component meets modern accessibility standards, providing an inclusive user experience.
Keyboard Navigation
Key | Description |
---|---|
Space | Toggles the switch. |
Enter | Toggles the switch. |