Monitoring the parent's CSS attribute in Angular 2

One of my directives dynamically adds the number of pixels corresponding to its parent element's right CSS attribute.

import { Directive, ElementRef, AfterViewInit } from "angular2/core"

 @Directive({
     selector: "[d]"
 })
 export class PositioningFromParent implements AfterViewInit {
     private el:HTMLElement

    constructor(el: ElementRef) {
        this.el = el.nativeElement
    }

    ngAfterViewInit() {
      let v = this.el.parentNode.getBoundingClientRect().right
      this.el.style[left] = v + "px"
    }
 }

Although it functions properly, I have noticed that when I resize the window, the parent element changes along with its right value. My directive does not automatically adjust to reflect this change. How can I watch and update the

this.el.parentNode.getBoundingClientRect().right
value in Angular2?

Appreciate any guidance on this matter.

Answer №1

When the event is triggered, pay attention to resizing and updating:

 @Directive({
     selector: "[d]"
 })
 export class PositioningFromParent implements AfterViewInit {
     private el:HTMLElement

    constructor(el: ElementRef) {
        this.el = el.nativeElement
    }

    ngAfterViewInit() {
      this.updateLeft();
    }

    @HostListener('window:resize') 
    updateLeft() {
      let v = this.el.parentNode.getBoundingClientRect().right
      this.el.style[left] = v + "px"
    }
 }

To control how often the code runs during a resize operation, refer to angular2: How to use observables to debounce window:resize.

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

Unable to connect to a style sheet

I'm in the process of developing a web application and I'm facing an issue with linking a stylesheet to my app. Check out my code below: <html> <head> <title>Bubble</title> </head> <link rel=" ...

Dividing one SVG into Multiple SVGs

I'm facing a challenge with loading an SVG overlay on a Google Map. The SVG file is quite large, about 50mb, resulting in a delay of around 10 seconds for it to load in the browser. One solution I'm considering is splitting the SVG into 171 smal ...

When using translate.get with an array of strings in Angular 5, the function will return both the keys and values, not just

Currently, I am utilizing Angular 5 to manage internationalization through ngx-translate within my code. To elaborate on the issue at hand, I have a data table that pulls information from a web service and displays it correctly. There is also a button tha ...

New to Jquery - Experiencing difficulties with menu animation

I've encountered a strange problem that I've been struggling to find a solution for, even after spending hours trying to Google it... The animation on 'mouseenter' and 'mouseleave' is working perfectly fine. However, the issu ...

Incorporate some flair into the Twitter iframe with a Style tag

I have been attempting to add a style tag into the head of an embedded Twitter timeline in order to customize some of the styling. I wrote the CSS and added it within a style tag. My initial idea was to inject this into the iframe using jQuery, but unfortu ...

Submitted input in a text field is automatically displayed in a separate text box

Below is a snippet of HTML code from my AngularJS application <input type="text" class="input-xlarge" id="user_name" ng-model="myModel.text" name="user_name" rel="popover" data-content="Enter your first and last name." data-original-titl ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

Navigation bar with a divider line along with an accompanying image

How can I position the image behind the navbar without any white line in between them? I've tried adjusting the positioning, z-index, and margin, but nothing seems to work. The website is built with Angular 6 and Bootstrap, and I know it's not th ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Sending various arguments within a single post request in Angular 6 and Node.js

I am currently developing an app in Angular 6 using NodeJS + Mongoose. I have two parameters that need to be sent to the backend with a single POST request. My query is, is it possible to include both parameters in one POST Request? Thank you The paramet ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

I am attempting to selectively add or remove a line-through style to a single item using Angular

I am facing an issue with my todo list app where I want to apply a line-through style to a specific item only, but currently, the line-through is being applied to all the items in the list instead of just the one I clicked on. HTML <input type="te ...

Responsive breakpoints in TailwindCSS seem to have an issue with applying padding and margin styles properly

Currently, I am tackling a project that involves creating a responsive design with Tailwind CSS on nuxtjs. Has anyone encountered the issue of py-8 applying to both breakpoints? If so, please share your insights! Here is how I have structured the compone ...

Issues arise when trying to use a JavaScript function within an HTML form, with an error message stating "TypeError: total

Recently, I encountered an issue with a straightforward JavaScript function that calculates user input. The function performed as expected when I tested it without the form tag. However, when I tried using the same code within the form tag, an error was di ...

Customizing the appearance of a submenu header on a WordPress website

I need assistance in creating a sub-menu style. Please refer to the image linked below for guidance: https://i.sstatic.net/Cu1on.jpg Here is my website link: ...

Combatting repetitive code through the use of Redux toolkit and actions

My code is currently long and repetitive. I realize that using helper functions would help me cut it down and make it more maintainable and readable. As a React beginner, I have a question: Should I implement most of this logic with helper functions in a s ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Dealing with undefined variables when importing into create-react-app Sass: SassError

I am using create-react-app with SCSS style-files. My project includes an App.scss file where I import all other .scss stylesheets, and a variables.scss file where I define all project variables. However, when I import variables.scss into App.scss and the ...

The sticky header is malfunctioning due to a null offsetTop value

import React , {useRef, useEffect} from 'react' import './header.css' const nav_links =[ { path:'#home', display:'Home' }, { path:'#about', display:'About& ...

Angular 4 lazy loading feature is malfunctioning

I've been working on implementing lazy loading in my angular4 project, following all the steps outlined in the documentation without success. Here is a snippet of my code: StudentModule: import { NgModule } from '@angular/core'; import { ...