Primitives
Toggle a button on and off.
import { Component, signal } from "@angular/core";
import { NgpButton } from "ng-primitives/button";
import { NgpToggle } from "ng-primitives/toggle";
@Component({
selector: "app-toggle",
imports: [NgpToggle, NgpButton],
template: `
<button [(ngpToggleSelected)]="selected" ngpButton ngpToggle>Toggle</button>
`,
styles: `
[ngpButton] {
padding-left: 1rem;
padding-right: 1rem;
border-radius: 0.5rem;
color: var(--ngp-text-primary);
border: none;
outline: none;
height: 2.5rem;
font-weight: 500;
background-color: var(--ngp-background);
transition: background-color 300ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: var(--ngp-button-shadow);
}
[ngpButton][data-hover] {
background-color: var(--ngp-background-hover);
}
[ngpButton][data-focus-visible] {
outline: 2px solid var(--ngp-focus-ring);
outline-offset: 2px;
}
[ngpButton][data-press] {
background-color: var(--ngp-background-active);
}
[ngpButton][data-selected] {
background-color: var(--ngp-background-inverse);
color: var(--ngp-text-inverse);
}
`,
})
export default class ToggleExample {
/**
* Whether the toggle is selected.
*/
readonly selected = signal(false);
}
Import the Toggle primitives from ng-primitives/toggle
.
import { NgpToggle } from 'ng-primitives/toggle';
Assemble the toggle directives in your template.
<button ngpToggle [(ngpToggleSelected)]="selected">Toggle</button>
Create a reusable component that uses the toggle directives.
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Toggle } from './toggle';
@Component({
selector: 'app-root',
imports: [Toggle, FormsModule],
template: `
<button [(ngModel)]="selected" app-toggle>Toggle</button>
`,
})
export default class App {
selected = signal(false);
}
Generate a reusable toggle component using the Angular CLI.
ng g ng-primitives:primitive toggle
path
: The path at which to create the component file.prefix
: The prefix to apply to the generated component selector.componentSuffix
: The suffix to apply to the generated component class name.fileSuffix
: The suffix to apply to the generated component file name. Defaults to component
.exampleStyles
: Whether to include example styles in the generated component file. Defaults to true
.The following directives are available to import from the ng-primitives/toggle
package:
Apply the `ngpToggle` directive to an element to manage the toggle state. This must be applied to a `button` element. Whether the toggle is selected.
Whether the toggle is disabled.
Emits when the selected state changes.
[ngpToggle]
ngpToggle
The following data attributes are applied to the ngpToggle
directive:
Attribute | Description |
---|---|
data-selected |
Applied when the toggle is selected. |
data-disabled |
Applied when the toggle is disabled. |
Copyright © 2025 Angular Primitives