Skip to content

Instantly share code, notes, and snippets.

@riapacheco
Created March 20, 2021 19:15
Show Gist options
  • Save riapacheco/f883e5a624cdba98b068699db704095c to your computer and use it in GitHub Desktop.
Save riapacheco/f883e5a624cdba98b068699db704095c to your computer and use it in GitHub Desktop.
Toggle component that tracks the state of 'on' and 'off'; and emits the value to the parent component. (up to parent component to ensure that current state of toggle is stored)
<a class="toggle-container" (click)="toggleClick()">
<div [ngClass]="toggleOn ? 'toggle-bg toggle-on' : 'toggle-bg'">
<div [@toggleTrigger]="toggleOn ? 'on' : 'off' " class="toggle"></div>
</div>
</a>
@import '~./src/app/scss/colors.scss';
.toggle-bg {
display: inline-block;
height: 1rem;
width: 2rem;
background-color: $accent-color;
border-radius: 3px;
position: relative;
.toggle {
width: 1rem;
display: inline-block;
background-color: white;
position: absolute;
left: 0.01rem;
top: 0;
bottom: 0;
margin: 0.1rem;
border-radius: 3px;
box-shadow: 2px 2px 12px #00000050;
}
}
.toggle-on {
background-color: $primary-color;
}
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'app-toggle',
templateUrl: './toggle.component.html',
styleUrls: ['./toggle.component.scss'],
animations: [
trigger('toggleTrigger', [
state('off', style({ transform: 'translateX(0%)' })),
state('on', style({ transform: 'translateX(70%)' })),
transition('on <=> off', [
animate('120ms ease-in-out')
])
])
]
})
export class ToggleComponent implements OnInit {
@Input() toggleOn: boolean;
@Output() toggledTo = new EventEmitter();
constructor() { }
ngOnInit(): void {
}
toggleClick(): any {
if (this.toggleOn) {
this.toggleOn = false;
this.toggledTo.emit('off');
} else {
this.toggleOn = true;
this.toggledTo.emit('on');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment