I am trying to attach a keyup event to a directive in my Angular project. Here is the directive:
angular.module('clinicalApp').directive('chatContainer', function() { return { scope: { encounter: '=', count: '=' } templateUrl: 'views/chat.container.html', link: function(scope, elem, attrs) { scope.count = 500; } }; });
And here is the html from the template:
<div class="span4 chat-container"> <div class="chat-body"> <form accept-charset="UTF-8" action="#" method="POST"> <div class="text-area-container"> <textarea id="chatBox" class="chat-box" rows="2"></textarea> </div> <div class="button-container btn-group btn-group-chat"> <input id="comment" class="btn btn-primary btn-small btn-comment disabled" value="Comment" ng-click="addMessage()"/> </div> </form> </div> </div> </div>
I want to access the chatbox
in my link function and attach the keyup event to it. I know I can get it with jQuery, but that cannot be the Angular way. What is the proper way to grab that element from the dom?
The code which working in . js file should work in . ts file, so if you are using document. getElementById("demo") in your JS file then this peice of code will also work in typescript file.
If DOM elements created by Angular, views will be created by default. If we use Jquery or JavaScript to change the DOM structure directly, then no views will be updated. Angular doesn't know that the DOM element is created. So change detection not works for that DOM element.
You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }
You can easily do it with Angular' element
' find()
method:
var chatbox = elem.find("textarea"); // Finding chatbox.bind("keyup",function(){ // Binding console.log("KEYUP!") })
Live example: http://jsfiddle.net/cherniv/S7XdK/
You can use element.find(yourSelector) as previously mentioned, but it is better to use ngKeyUp, similar to how you would use ngClick:
https://docs.angularjs.org/api/ng/directive/ngKeyup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With