Enhancing NG Style in Angular 6 using a custom function

Today, my curiosity lies in the NG Style with Angular 6. Specifically, I am seeking guidance on how to dynamically update [ngStyle] when utilizing a function to determine the value.

To better illustrate my query, let me present a simplified scenario: I have an array of objects that populate div elements. Each section consists of two divs - one on the left and one on the right.

The width of the left div varies based on its content, ranging from 50px to 125px. Meanwhile, I aim to have the right div adjust its size to half of its adjacent left div (as determined by getLeftDivHeight method) within each section (Container).

My primary challenge is figuring out how to trigger ngStyle updates whenever the height of the left div changes due to resizing, content additions, or page rendering.

Below is the code snippet:

HTML

<section class = "Container" *ngFor="let oneContent of allContent">

<div id="{{oneContent.id}}" style="float: left">
<p> {{oneContent.Content}} </ p>
</div>

<div style="float: right" [ngStyle]="{'height': getLeftDivHeight(oneContent.id, 2)}">
</div>

</div>

Typescript (relevant function only)

getLeftDivHeight(id: string, divisionNumber: number): string {
const height = document.GetElementById(id).getBoundingClientRect().height / 
divisionNumber;
return height + 'px';
}

Please note that my quest for a solution revolves around Angular rather than HTML techniques. The provided code serves solely to articulate the issue at hand.

Your insights are appreciated!

Answer №1

If you need to retrieve the entire style string, like width: 50%, you can do so by calling the getLeftDivHeight function.


getLeftDivHeight(id: string, divisionNumber: number): string {
    let height = document.getElementById(id).getBoundingClientRect().height / divisionNumber;
    return `height: ${height}px`;
}

Alternatively, you can implement the following syntax within your template


[style.height.px]="getLeftDivHeight(parameters)"
which will only give you the numerical height value from the method.

Answer №2

After some trial and error, I finally figured it out by using a directive.

I relied on ElementRef to tap into the HTML Object of my designated right div.

import {ElementRef,Renderer} from '@angular/core';
constructor(private el: ElementRef,public renderer: Renderer) {}

Next, I leveraged Dom to ascertain the height of the left div

this.el.nativeElement.parentElement.childElement[0].clientHeight;

To inject style, I utilized this.renderer.setElementStyle()

It was also a valuable lesson to steer clear of using offscrollheight for calculations!

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

Combining photos seamlessly and bringing them to life through animation upon window loading

My main goal is to seamlessly fit the images together, but I'm struggling to achieve this. I tried using masonry, but unfortunately it didn't work for me. All I want is to tightly pack the divs together. For instance, in my fiddle example, I woul ...

`A mistake occurred while building in the package.json file`

While attempting to run all build processes by using the command npm run build:css, I encountered an error indicated below. Even after running npm cache clean --force, the issue remains unresolved. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm E ...

Different categories of "areas" found in TypeScript within Visual Studio 2013

In C#, we often use "regions," but unfortunately that feature is missing in TypeScript. Is there a way to group code sections in TypeScript? I came across this article on Stack Overflow discussing the absence of regions in TypeScript. I'm curious if ...

Positioning elements vertically and float them to the left side

I'm struggling to grasp the concept of the float attribute. Here's the code that is causing me confusion: #p1 { border: solid black 3px } <p id="p1" style="float:left">Paragraph 1</p> <a href="https://facebook.com" style="floa ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

Issue encountered with Mongoose: Error 404 occurs while attempting to delete an object from a collection

I've encountered a strange issue with a mongoose API that is supposed to remove an object from a collection. When I call the API and pass the ID as a parameter (I have verified that the ID exists), I receive a 404 response. Here's how I am call ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Scrolling Horizontally with a <div> containing <a> and <img> elements

I currently have a table with three columns. The third column consists of multiple images that are clickable to perform an action, so I need this column to be horizontally scrollable. To achieve this, I inserted a <div> in the third column and added ...

Encountering a Node V18 Peer Dependency Conflict错

Can someone please help me understand what's causing this error? Every time I try to install a dependency, this keeps popping up. I'm completely lost and unsure of what's happening. npm ERR! 1 more (the root project) npm ERR! peer ...

Efficient management of pre-built assets in Vite

I am currently developing a Vue application using Vite. Within the content folder, I have numerous files (ranging from 10 to 100) located as follows: content/block/paragraph.json content/block/theorem.json content/inliner/link.json ... My goal is to creat ...

Can you explain to me the relationship between Node.js and Angular? Is it primarily for creating APIs or does

I've been trying to find information on Google about this, but I haven't found a satisfactory answer. Can someone explain the role of Node.js and ExpressJS in MEAN stack development? Is it similar to PHP for creating APIs that Angular will then c ...

Customizing Material UI CSS in Angular: A Guide

Recently, while working with the Mat-grid-tile tag, I noticed that it utilizes a css class called .mat-grid-tile-content, which you can see below. The issue I am encountering is that the content within the mat-grid-tile tag appears centered, rather than f ...

I am encountering an issue where body-parser is not functioning properly with typescript. Whenever I make a request, the request.body is returning as undefined

Below is the code snippet for my Express application using TypeScript version 3.7.4: import bodyParser from "body-parser"; import config from "config"; import cookieParser from "cookie-parser"; import express from "express"; import mongoose from "mongoose ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

What is causing the spinner with CSS rotation transform to bounce rhythmically?

In my design, I have created a simple Spinner icon in Figma. It's meant to be perfectly aligned at the center of an enclosing frame that has dimensions of 64x64. To achieve the rotating effect, I applied CSS rotation as shown below: let rotation = ...

Tips for utilizing angular and express to transmit data via a server and troubleshooting a 404 error

I am currently working on integrating user registration functionality in my frontend using Angular and sending the data to a server (Express). I seem to be facing some issues with the implementation. Does anyone have a solution to this problem? I have set ...

There are no matching overloads in React for this call

Below is an error message in the code. It seems to be related to the usage of <IHistorical[]> in useQuery, but unfortunately, I haven't found a solution for it yet. Overload 1 of 2, '(props: Props | Readonly<Props>): ReactApexChart& ...

Implementing a fixed div with jQuery scrolling

I need the left div to stay in sync with the scrolling content. However, there is a challenge because this div is taller than the screen. I want the user to be able to see the bottom of the left div when they reach the bottom of the page. My solution invo ...

Disable a tab or menu item if the bean's boolean value is 'false'

I designed a home page with various menu/tab options that redirect the user when clicked, but only if they have access to that specific item. If access is not granted, the menu item becomes unclickable. While this functionality works, I am interested in en ...

What causes multiple links to have an active class when using Angular2's routerLinkActive?

I am currently trying to incorporate routerLinkActive into my application, but I am encountering an issue where the active class is being applied to multiple links. Here's how I have implemented it: <ul class="nav nav-tabs"> <li r ...