Struggling with creating a custom counter input component where the input value is controlled by custom increment/decrement buttons.
Desired output:
https://i.sstatic.net/oYl1g.png
Content projection will be used to expose the input for form usage and adding properties like a regular number input. Considering using a directive on the input:
<my-counter-input>
<input [(ngModel)]="count" myInputRef />
</my-counter-input>
The component includes two buttons and a ng-content
-slot:
<button (click)="decrement()">-</button>
<ng-content select="input"></ng-content>
<button (click)="increment()">+</button>
So far, all seems well. Interaction with the directive can be done using the @ContentChild
decorator.
@Component({
selector: 'my-counter-input',
templateUrl: './counter-input.component.html',
styleUrls: ['./counter-input.component.scss'],
})
export class CounterInputComponent {
@ContentChild(InputRefDirective)
public input: InputRefDirective;
constructor() {}
public increment() {
this.input.increment();
}
public decrement() {
this.input.decrement();
}
}
An issue arises when trying to bind the value of the input element to the directive; neither the increment nor decrement method affects the native input value. Struggling with achieving a two-way binding on the native input value.
@Directive({
selector: 'input [myInputRef]',
})
export class InputRefDirective {
@HostBinding('type') readonly type = 'number';
@HostBinding('value') value = 5;
public increment() {
this.value++;
}
public decrement() {
this.value--;
}
}
Uncertain on the next steps. How can the value of the native input be updated along with triggering the native change event?