Reputation: 13387
So I am taking the plunge and learning angular 4. So far everything is pretty straight forward apart from my understanding of directives. I want to create a directive that will resize an element based on it's width. In angularJs, this would have been done something like this:
angular.module('buzzard.directives')
.directive('bzAnswers', directive)
.controller('BzAnswersController', controller);
function directive($window, $timeout) {
return {
restrict: 'A',
link: lnkFn,
controller: 'BzAnswersController',
controllerAs: 'controller'
};
function lnkFn(scope, element, attrs, controller) {
var window = angular.element($window);
controller.resize(element);
window.bind('resize', function () {
$timeout(function () {
controller.resize(element);
});
});
};
};
function controller() {
var self = this;
// Method binding
self.resize = resize;
//////////////////////////////////////////////////
function resize(parent) {
var children = parent.children();
angular.forEach(children, function (child) {
var anchor = child.getElementsByTagName('a');
if (anchor.length === 1) {
var element = anchor[0];
var dimensions = element.getBoundingClientRect();
angular.element(element).css('height', dimensions.width * .5 + 'px');
}
});
};
};
So my question is, how would you go about doing that in angular 4? And yeah, I am using typeScript :)
Upvotes: 0
Views: 197
Reputation: 222760
The direct counterpart to AngularJS event listeners on directive element, window
or document
is HostListener
decorator:
@Directive(...)
export class SomeDirective {
@HostListener('window:resize', ['$event'])
onResize(e) {
this.resize();
}
...
}
See also this answer on how HostListener
and HostBinding
decorators translate to AngularJS.
Upvotes: 2