I have a reactive form for which the from controls has an array and loop the array to produce a reactive form - my problem is that I want to add a directive for controls that accept only numbers - if I add it in the loop like below it adds the directive in all my input
types.
<ng-container *ngFor="let formInput of emergencyContactForm">
<ng-container [ngSwitch]="formInput.controlType">
<div *ngSwitchCase="'input'" class="col-4 mb-3" [formGroup]="emergencyContactDetails">
<label [attr.for]="formInput.key">{{formInput.label}}</label>
<input [formControlName]="formInput.key" [type]="formInput.type" appNumbericInput />
<span [appDynamicFormsValidationMessages]="emergencyContactDetails.controls[formInput.key]" [formInputInstance]="formInput"></span>
</div>
</ng-container>
</ng-container>
appNumbericInput
is the directive used to restrict the user to enter only numbers in the input type text - But I don't want this directive to be added in all my input
fields - My question is that Is there a way to bind the directives
to the form control like adding validation
to the form control
NumbericInputDirective.ts
@Directive({
selector: '[appNumbericInput]',
})
export class NumbericInputDirective {
constructor() { }
@HostListener("keypress", ['$event']) onkeypress(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
@HostListener('paste', ['$event'])
paste(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
@HostListener('keyup', ['$event']) onKeyUp(event) {
let el = <HTMLSelectElement>event.target;
if (el.value != "") {
let charList = el.value.substring(0, el.value.length);
if (charList[0] === "0") {
el.value = el.value.substring(1, el.value.length);
}
}
}
}