-
Notifications
You must be signed in to change notification settings - Fork 0
/
altcha.component.ts
65 lines (57 loc) · 1.72 KB
/
altcha.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { CUSTOM_ELEMENTS_SCHEMA, Component, ElementRef, ViewChild, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from '@angular/forms';
@Component({
selector: 'app-altcha',
standalone: true,
templateUrl: './altcha.component.html',
styleUrls: ['./altcha.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AltchaComponent),
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => AltchaComponent),
multi: true
}
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AltchaComponent implements ControlValueAccessor, Validator {
@ViewChild('altchaWidget', { static: true }) altchaWidget!: ElementRef;
value: string = '';
onChange: any = () => {};
onTouched: any = () => {};
ngAfterViewInit(): void {
const el = this.altchaWidget.nativeElement as HTMLElement;
el.addEventListener('statechange', (ev) => {
const { detail } = ev as CustomEvent;
if (detail) {
const { payload, state } = detail;
this.onStateChange(state, payload);
}
});
}
writeValue(value: any): void {
this.value = value;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
validate(control: AbstractControl): ValidationErrors | null {
if (!this.value) {
return { required: true };
}
return null;
}
onStateChange(state: 'unverified' | 'verifying' | 'verified' | 'error', payload: string = '') {
this.value = state === 'verified' ? payload : '';
this.onChange(this.value);
this.onTouched();
}
}