Skip to content

Instantly share code, notes, and snippets.

@dcagnetta
Created May 24, 2022 09:09
Show Gist options
  • Save dcagnetta/4a182bb5728b167db2d104069c5358a7 to your computer and use it in GitHub Desktop.
Save dcagnetta/4a182bb5728b167db2d104069c5358a7 to your computer and use it in GitHub Desktop.
Control Value Accessor
<button (click)="updateValue(+value - 1)">-</button>
<input [ngModel]="value"
(ngModelChange)="updateValue($event)"
type="string">
<button (click)="updateValue(+value + 1)">+</button>
<app-quantity-input [(ngModel)]="quantity"></app-quantity-input>
<div>
Quantity: {{ quantity }}
</div>
<button (click)="updateValue(+value - 1)">-</button>
<input [ngModel]="value"
(ngModelChange)="updateValue($event)"
type="string">
<button (click)="updateValue(+value + 1)">+</button>
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subject } from 'rxjs';
@Component({
selector: 'app-quantity-input',
templateUrl: './quantity-input.component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => QuantityInputComponent),
multi: true,
}],
})
export class QuantityInputComponent implements ControlValueAccessor {
value: number;
disabled = false;
private valueChanges = new Subject<number>();
private touches = new Subject();
registerOnChange(fn: any) {
console.log('registerOnChange',fn);
this.valueChanges.subscribe(fn);
}
registerOnTouched(fn: any) {
this.touches.subscribe(fn);
}
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
writeValue(value: number) {
this.value = value;
}
updateValue(value: number) {
this.value = value;
this.valueChanges.next(value);
}
touch() {
this.touches.next();
}
}