my solution to this problem is to add in the root component ngAfterContentChecked
and there to select all my relevant elements and add the event. example:
ngAfterContentChecked() {
//console.log('MASTER ngAfterContentChecked')
let rgx = /^[0-9,\.]+$/;
let preventNonNumber = e => {
//let v = (e.target as HTMLInputElement).value
if (
// Allow: Delete, Backspace, Tab, Escape, Enter
[46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
(e.keyCode === 65 && e.ctrlKey === true) || // Allow: Ctrl+A
(e.keyCode === 67 && e.ctrlKey === true) || // Allow: Ctrl+C
(e.keyCode === 86 && e.ctrlKey === true) || // Allow: Ctrl+V
(e.keyCode === 88 && e.ctrlKey === true) || // Allow: Ctrl+X
(e.keyCode === 65 && e.metaKey === true) || // Cmd+A (Mac)
(e.keyCode === 67 && e.metaKey === true) || // Cmd+C (Mac)
(e.keyCode === 86 && e.metaKey === true) || // Cmd+V (Mac)
(e.keyCode === 88 && e.metaKey === true) || // Cmd+X (Mac)
(e.keyCode >= 35 && e.keyCode <= 39) // Home, End, Left, Right
) {
return; // let it happen, don't do anything
}
if (rgx.test(e['key']) == false) {
e.preventDefault();
}
};
let inputs = document.querySelectorAll('label-input[numberOnly] input, cbx-label-input[numberOnly] input')
//console.log(inputs)
inputs.forEach(i => (i as HTMLInputElement).onkeydown = preventNonNumber)
}
NOTICE that the ngAfterContentChecked gets fired everytime you touch an input, so the selector runs everytime again, and also setting of the function, but since its a static function that your just override there isn't so much of a performance problem.