简体   繁体   中英

Angular 4 vs AngularJs directives

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM