bitwarden-estensione-browser/libs/angular/src/directives/true-false-value.directive.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-12-16 13:36:21 +01:00
import { Directive, ElementRef, forwardRef, HostListener, Input, Renderer2 } from "@angular/core";
2022-02-22 15:39:11 +01:00
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
2018-06-06 20:29:59 +02:00
// ref: https://juristr.com/blog/2018/02/ng-true-value-directive/
@Directive({
2021-12-16 13:36:21 +01:00
selector: "input[type=checkbox][appTrueFalseValue]",
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TrueFalseValueDirective),
multi: true,
},
],
2018-06-06 20:29:59 +02:00
})
export class TrueFalseValueDirective implements ControlValueAccessor {
2021-12-16 13:36:21 +01:00
@Input() trueValue = true;
@Input() falseValue = false;
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
@HostListener("change", ["$event"])
onHostChange(ev: any) {
this.propagateChange(ev.target.checked ? this.trueValue : this.falseValue);
}
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
writeValue(obj: any): void {
if (obj === this.trueValue) {
this.renderer.setProperty(this.elementRef.nativeElement, "checked", true);
} else {
this.renderer.setProperty(this.elementRef.nativeElement, "checked", false);
2018-06-06 20:29:59 +02:00
}
2021-12-16 13:36:21 +01:00
}
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
registerOnTouched(fn: any): void {
/* nothing */
}
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
setDisabledState?(isDisabled: boolean): void {
/* nothing */
}
2018-06-06 20:29:59 +02:00
2021-12-16 13:36:21 +01:00
private propagateChange = (_: any) => {
/* nothing */
};
2018-06-06 20:29:59 +02:00
}