Listen for changes in the div height in Angular 2 using HostListener

After spending hours researching Event Listeners in Angular 2, it's clear that there is a lack of comprehensive documentation on the topic.

My goal is to set the height of various div groups (generated using ngFor) to match the height of the tallest one. This functionality was easily achieved in Angular 1 example

I understand that concepts like scope and $watch no longer apply in Angular 2. In my attempt to use Host Listener for this task, I have struggled to find useful documentation. While there are tutorials for common events like "click" or "mouseover", resources for other possible events such as $watch or onChange are lacking. Any documentation listing available event names would be greatly appreciated.

If possible, I would also love to see an example in Angular 2 based on the link provided above.

PS: I came across 'window: resize' which works, but 'div: resize' does not seem to have the desired effect.

EDIT: Thanks to some guidance from Maximus, I was able to get it working. Here is the code snippet:

An additional directive file was created:

comments.directive.ts

import { Directive, ElementRef, Input } from '@angular/core';
import { DoCheck } from '@angular/core';

@Directive({ selector: '[comments]' })

export class CommentsDirective implements DoCheck{

    style: any;

    constructor(private element: ElementRef) {

    }

    ngDoCheck() {
        console.log(this.element);
        this.style = { //shared scope variable 'style'
            height:this.element.nativeElement.offsetHeight+'px',
            width:this.element.nativeElement.offsetWidth+'px'
        };
    }
}

The directive was then imported into the NG-Module.

HTML Section:

<div comments [ngStyle]="style">

Once I implement the part where all heights are equalized to match the tallest, I will update it accordingly.

Answer №1

It is important to note that scope and $watch are no longer part of Angular.js

Angular triggers watchers during the digest cycle. In Angular, a similar concept is present where it triggers ngDoCheck during the digest cycle. For more information, you can visit here.

Incorporating the example provided for Angular.js, here's how you can achieve a similar functionality in Angular:

@Directive({
   selector: '[HeightSetter]'
})
class HeightSetter {
   style: any;

   constructor(private element: ElementRef) {

   }

   ngDoCheck() {
     this.style = { //scope variable style, shared with our controller
         height:this.element.nativeElement.offsetHeight+'px', //set the height in style to our elements height
         width:this.element.nativeElement.offsetWidth+'px' //same with width
     };
   }
}

HTML

<span HeightSetter [ngStyle]="style"></span>

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

Problem encountered when attempting to utilize the spread operator within .vue files in an Elixir Phoenix 1.3 application

I'm facing an issue while building Vue.js components that involve using the spread operator to map states from Vuex within my Phoenix 1.3 application. The JavaScript compile errors I encountered are causing some roadblocks: 26 | }, 27 | compu ...

Issues arising from utilizing Twitter Bootstrap 3.1.x, the box-sizing property, and Revolution Slider

I'm currently working on a PyroCMS theme that is built with Twitter Bootstrap 3.1.x and includes Revolution Slider. However, I've encountered an issue where the property box-sizing: border-box; creates an unwanted grey border as shown in the imag ...

RxJS - Only emit if another source does not emit within a specified time frame

Imagine having two observables. Whenever the first one emits, there should be a 2-second pause to check if the other observable emits something within that timeframe. If it does, then no emission should occur. However, if it doesn't emit anything, the ...

When traversing across different child elements, the MouseEvent.offsetX/Y values get reset to 0

Check out this interactive example. The demonstration includes a main div with 3 child divs. A click event is triggered on the main div, but instead of displaying alerts with the mouse position relative to the parent div as expected, it shows the position ...

Vuejs - Expanding Panels

Trying to implement an accordion using Vue.js has been a bit challenging for me. While I came across some examples online, my requirements are slightly different. In order to maintain SEO compatibility, I need to use "is" and "inline-template", which make ...

Using the "Range" Input Type in Angular's Reactive Forms

I'm having difficulties with styling the background of my slider/range in reactive forms within Angular. The input value updates correctly, but the issue arises when I try to type in the input field - the range changes, but the color (green) remains s ...

I am looking for a way to retrieve the ids of all div elements that have the same x coordinate using document.elementFromPoint in JavaScript. Can someone help me with

Currently, I am facing an issue where I have two divs positioned at the same x coordinate. I am attempting to retrieve the IDs of both divs using document.elementFromPoint(). However, I am only able to receive the ID of one div. var elem = document.elem ...

Date parsing error thrown by jQuery datepicker plugin

What could be causing the InvalidDate exception when attempting to parse the date using $.datepicker.parseDate("mm/yy","02/2008");? ...

Is there a way to add a class (1) when scrolling to a specific div, and then switch from class (1) to class (2) when moving away from the

How can I create a JavaScript function that adds the class "animated fadeInDown" to div id hover1 when I reach or scroll to it? Also, when I scroll down or leave div id hover1, how do I change the class from "animated fadeInDown" to "animated fadeOutUp"? ...

Remove httpOnly cookies in Express

Can browser cookies with the attribute HttpOnly:true be deleted? Here is a snippet of my login endpoint: async login(@Ip() ipAddress, @Request() req, @Res() res: Response) { const auth = await this.basicAuthService.login(req.user, ipAddress); ...

Python.Selenium. Unable to locate current element. Techniques for switching frames

I am trying to collect feedback from a specific page at this URL. After waiting for the page to load, I attempted to locate elements using Google Chrome inspector. However, Selenium is unable to find these elements, and I also could not find them in the p ...

Retrieving radio button values in React from a different component

I am dealing with a child component that contains radio buttons, each with its own value. I have imported this child component into a parent component to manage its state from the parent component. With the child component added, I need to access all the i ...

Reactstrap: Is it necessary to enclose adjacent JSX elements within a wrapping tag?

While working on my React course project, I encountered an issue with my faux shopping website. The error message that keeps popping up is: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...& ...

React Native is facing difficulty in fetching pagination data which is causing rendering errors

Currently, I am working on fetching pagination data from an API. The process involves retrieving data from https://myapi/?page=1, then from https://myapi/?page=2, and so on. However, despite following this logic, I encountered an error that has left me puz ...

Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

Tips for managing your time while anticipating an observable that may or may not

I am facing a dilemma in my Angular app where I need to conditionally make an HTTP call to check for the existence of a user. Depending on the result of this call, I may need to either proceed with another API request or halt the processing altogether. I ...

Issue with Calendar Control not loading in Internet Explorer 9 when using ASP

I have been trying to incorporate a calendar control in my code that selects a date and returns it to a text field. It worked perfectly fine on browsers prior to IE 8, but I'm facing issues with IE 9. Can someone help me troubleshoot this problem and ...

Trouble encountered in aligning two DIVs in a horizontal position

I have been through numerous discussions on the same problem, but none of the solutions seem to work in my case. I am currently working on a section of my website that has 3 small boxes, each containing an image on top and text below. The issue arises when ...

Tips for implementing an AJAX request to retrieve data in real-time as the user types into a text input field

I am looking to add a feature where, upon entering text into the following input: <input path="tags" id="input-search"/> a list of suggested tags should appear similar to https://i.sstatic.net/oKWRr.png after making an ajax call. Here is the data ...