How to bind a custom directive to all input elements?

Viewed 1601

I have a custom directive called HandleScroll and I need to add this directive to all input elements. When I initially built it , it was only needed on one input elements so I added it manually as:

< Input handle-scroll....

But now I realize that I need to add this directive to each and every input element. Is there an easy way to do this using Javascript or will I have to sit and manually add this directive to each input tag ?

Update----Thank you everyone for your help, due to some updates I no longer need to use the directive , but need to bind an event listener to each input field. I've posted the new question at: Adding an event listener to each input field , if you can help please do , I greatly appreciate it !

3 Answers

In your directive class, you can set the selector in your decorator :

@Directive({
    selector: 'input'
})
export class HandleScroll...

You can wrap input with angular component. And just use the component everywhere.

<app-input-with-directive></app-input-with-directive>

In AngularJS you can use following.

function MyCtrl($scope, $compile, $window, $document) {
 $window.onload = function() {
    var inputs = $document[0].querySelectorAll('input');

  inputs.forEach(input => {
    input.setAttribute('handle-scroll', true);

    $compile(input, $scope);
  });
 };
}

Basically, we are trying to add a new attribute to each input element on the page and recompiling the element.

Related