Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code resembling the following:

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');
            }
        });
    };
};

Now, the burning question: How would one achieve this in Angular 4? And yes, I am coding in TypeScript :)

Answer №1

When it comes to AngularJS event listeners on directive elements, window, or document, the direct equivalent is using the HostListener decorator:

@Directive(...)
export class SomeDirective {
    @HostListener('window:resize', ['$event'])
    onResize(e) {
        this.resize();
    }

    ...
}

For more information about how HostListener and HostBinding decorators correspond to AngularJS, check out this answer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Retrieving and storing state in session storage with React

My webpage features a sidenav with expansion panels that can be opened and closed. I am currently working on setting the state to keep track of which expansion panel is open. However, when I click on one of the items in the sidenav, I get redirected to a ...

The nodeJS function is still returning an error message, despite successfully saving the JSON data in MongoDB

Recently delving into nodeJS and mongoDB for the first time. Working on an application that utilizes nodeJS as the middleware, mongoDB as the database, and angularJS in the user interface. In nodeJS, I have set up controllers and models to handle business ...

Choose Selectize.js to auto-populate inputs

I am currently using selectize.js for my project: $("#abc").selectize({ valueField: 'name', labelField: 'name', searchField: ['name'], plugins: ['remove_button'], createOnBlur: true, ...

Creating a multi-step progress bar in Yii2 that showcases completed steps using jQuery

Is there a way to automatically transition from one state to another once the order status changes in Yii2? var i = 1; $('.progress .circle').removeClass().addClass('circle'); $('.progress .bar').removeClass().addClass(&a ...

Why do rows in the React-bootstrap grid layout overlap when the screen is resized?

I am working on a simple layout structure with 2 rows: Row 1 consists of 2 columns Row 2 consists of 1 column The goal is to have both rows expand in width and avoid vertical scrolling of the page. However, when resizing the screen, I want the columns of ...

What is the process for retrieving my dates from local storage and displaying them without the time?

Having an event form, I collect information and store it in local storage without using an API. However, I face a challenge when extracting the startdate and enddate out of localstorage and formatting them as dd-mm-yyyy instead of yyyy-mm-ddT00:00:00.000Z. ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

Utilize Google Tag Manager to Safely Gather Specific Data

My current project involves capturing values from a <select> element, sending them to the Data Layer, and then forwarding them to an Analytics account via Google Tag Manager. The source code I'm trying to extract values from includes a dynamic s ...

Animating each individual element within the v-for loop in Vue.JS

Recently, I developed a basic to-do app using VueJS. Additionally, I integrated vue2-animate, which is a Vue.js 2.0 adaptation of Animate.css used for Vue's built-in transitions. The animation feature that adds an element functions correctly. However ...

An array variable marked as mat-checked contains the total sum

Currently, I am utilizing mat-checked to calculate a total sum from an Array. The issue arises when the number of items in my array varies, triggering an error: ERROR TypeError: Cannot read property 'isChecked' of undefined Is there a way to ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

There was a TypeScript error found at line 313, character 9 in the file @mui/material/styles/experimental_extendTheme.d

Encountering Typescript error while using Material UI component for date range picker Link - https://mui.com/x/react-date-pickers/date-range-picker/ Snippet of the code import * as React from 'react'; import { Dayjs } from 'dayjs'; im ...

I am encountering TypeError issues while attempting to mock/test Vuex store modules

I'm currently in the process of learning how to effectively test components and JavaScript code, but I have hit a roadblock with Vuex modules. Below is the code snippet for the test: import { shallowMount } from '@vue/test-utils' import Wor ...

Encountered a problem when trying to import the function "createToken" into a Node.js middleware

I have developed a model called users in which I included a method named generateToken for generating web tokens. This model is being used with the Sequelize ORM. module.exports = (sequelize, Sequelize) => { const Tutorial = sequelize.define("u ...

Emphasize SELENIDE rows

My goal is to achieve the following: @Test public void tableTest() { getDriver().get(BASE_URL + "tabulka.php"); List<WebElement> rows = getDriver().findElements(By.xpath("//table//tbody//tr")); for (We ...

Express server encountering difficulties locating requested file for download

I encountered a curious issue while working with my express server: I am attempting to download a file from a dynamically created folder. Below is the code snippet: var folder = id.toString() var file = [projectRoot,"/app/temp/",folder, "/regist ...

Guide to utilizing the app.locals parameter in JavaScript?

Currently I am in the process of developing a node.js application. In my app.js file, I have loaded a JSON file as app.locals.parameter and now I am attempting to utilize it in my index.hbs. Let's assume: app.locals.componentData = require('./m ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...