🐦 Grab your early bird tickets for the next NativeScript conference! jsMobileConf is coming back to Boston.

NativeScript Angular

Switch

The switch component allows users to toggle a control between two states. The default state of the component is off, or false, however you can change the state by setting the checked property to a boolean value. To handle the state change event you can use the checkedChange property, which notifies the app when the value has changed. Another useful feature of the component is the isEnable property, which gives the functionality to make the component inactive.

Image

Basic Switch

HTML

<Switch checked="true" (checkedChange)="onCheckedChange($event)" class="m-15" row="1" col="1"></Switch>

Handle checkedChange event and setting default value.

// import { Switch } from "tns-core-modules/ui/switch";
// import { EventData } from "tns-core-modules/data/observable";

onCheckedChange(args: EventData) {
    let mySwitch = args.object as Switch;
    let isChecked = mySwitch.checked; // boolean
}

Improve this document

Demo Source


Disable Switch

Disabling the Switch control via setting its isEnabled boolean property to false.

<Switch #switch isEnabled="true" class="m-15"></Switch>

<Button [text]="switch.isEnabled ? 'Disable switch' : 'Enable switch'" (tap)="switch.isEnabled = !switch.isEnabled"
    horizontalAlignment="stretch" class="btn btn-primary btn-active"></Button>

Improve this document

Demo Source


Styling Switch

The styling properties for the Swtich control are as follows:

  • color- Controls the handle color
  • bacxgroundColor(background-color in CSS) - Controls the background color while the switch is in ON state.
    • offBackgroundColor (off-background-color in CSS) - Controls the background color while the switch is in OFF state.
<!-- Styling via inline properties ---->
<Switch color="yellow" backgroundColor="green" offBackgroundColor="red">
</Switch>
<!-- Styling via CSS class (see CSS file) ---->
<Switch class="m-15 secondSwitchStyle" checked="true">
</Switch>
<!-- Applying style & opacity via CSS class ---->
<Switch class="m-15 thirdSwitchStyle" checked="true">
</Switch>
.secondSwitchStyle{
    color: yellow;
    background-color: green;
    off-background-color: red;
}

.thirdSwitchStyle{
    opacity: 0.8;
    color: darkblue;
    background-color: lightseagreen;
    off-background-color: orangered;
}

Improve this document

Demo Source


API Reference for the Switch Class

Native Component

Android iOS
android.widget.Switch UISwitch