| 58 | |
| 59 | describe('ControlValueAccessor', () => { |
| 60 | @Component({ |
| 61 | selector: 'custom-control', |
| 62 | template: ` |
| 63 | <input |
| 64 | [value]="value" |
| 65 | [disabled]="disabled" |
| 66 | (blur)="onBlur()" |
| 67 | (input)="onInput($event.target.value)" |
| 68 | /> |
| 69 | `, |
| 70 | providers: [{provide: NG_VALUE_ACCESSOR, useExisting: CustomControl, multi: true}], |
| 71 | changeDetection: ChangeDetectionStrategy.Eager, |
| 72 | }) |
| 73 | class CustomControl implements ControlValueAccessor { |
| 74 | value = ''; |
| 75 | writeCount = 0; |
| 76 | disabled = false; |
| 77 | |
| 78 | private onChangeFn?: (value: string) => void; |
| 79 | private onTouchedFn?: () => void; |
| 80 | |
| 81 | writeValue(newValue: string): void { |
| 82 | this.value = newValue; |
| 83 | this.writeCount++; |
| 84 | } |
| 85 | |
| 86 | registerOnChange(fn: (value: string) => void): void { |
| 87 | this.onChangeFn = fn; |
| 88 | } |
| 89 | |
| 90 | registerOnTouched(fn: () => void): void { |
| 91 | this.onTouchedFn = fn; |
| 92 | } |
| 93 | |
| 94 | setDisabledState(disabled: boolean): void { |
| 95 | this.disabled = disabled; |
| 96 | } |
| 97 | |
| 98 | onBlur() { |
| 99 | this.onTouchedFn?.(); |
| 100 | } |
| 101 | |
| 102 | onInput(newValue: string) { |
| 103 | this.value = newValue; |
| 104 | this.onChangeFn?.(newValue); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | @Directive({ |
| 109 | selector: '[cvaDir]', |