Skip to content

Instantly share code, notes, and snippets.

@isaacplmann
Last active October 3, 2017 14:06
Show Gist options
  • Save isaacplmann/47b294665bb8bb3003dcd04fc46061ac to your computer and use it in GitHub Desktop.
Save isaacplmann/47b294665bb8bb3003dcd04fc46061ac to your computer and use it in GitHub Desktop.
@Directive({
exportAs: 'ngxToggle',
selector: 'ngxToggle',
})
export class ToggleDirective {
defaultOn: boolean = false;
toggled: EventEmitter<boolean> = new EventEmitter();
private _on: boolean;
@HostBinding('attr.aria-expanded')
get on() {
return this.isOnControlled() ? this._on : this.state.on;
}
set on(state = !this.getOn()) {
if (this.isOnControlled()) {
this._on = state;
this.toggled.emit(state);
} else {
this.state = {
on: state,
}
this.toggled.emit(this.getOn());
}
}
state = {
on: this.getOn({on: this.defaultOn}),
}
@HostBinding('attr.aria-controls')
controls: string = 'target';
constructor(
@Optional() private defaultProps: NgxToggleDefaultProps,
) {
if (defaultProps) {
this.defaultOn = defaultProps.defaultOn;
}
}
isOnControlled() {
return this._on !== undefined
}
setOn = this.setOnState.bind(this, true)
setOff = this.setOnState.bind(this, false)
toggle = this.setOnState.bind(this, undefined)
}
@Component({
selector: 'my-app',
template: `
<button ngxToggle #toggle="ngxToggle" (click)="onClick()" (toggled)="onToggled($event)">
Toggle me
</button>
<div>{{toggle.on ? 'Toggled On' : 'Toggled Off'}}</div>
`,
})
export class AppComponent {
onClick() {
alert('you clicked!');
}
onToggled(value: boolean) {
alert(`Toggle value: ${value}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment