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

Transferring information between components, specifically when one of them is a routerOutlet within an Angular application

I need to transfer data from the category component to the product component within the dashboard component. However, I am facing an issue due to the presence of a router outlet inside the product component. View Dashboard Screen dashboard.component.html ...

I'm looking to add CSS transitions, like fade-ins, to a list of items in React in a way that the animations occur one after the other upon rendering. How can this be achieved?

I've scoured the depths of Stack Overflow and combed through countless pages on the internet in search of an answer to my query, but alas, I have not found a solution. So, my apologies if this question is a duplicate. Here's my conundrum: https ...

Avoid unnecessary extra margin on CSS div elements

Currently working with Bootstrap4. In a row with 2 col-md-6 (totaling 12 columns for the row). However, experiencing an unwanted margin on the left column as shown in the image below. How can I remove it? https://i.sstatic.net/u5oix.png html: <hea ...

Locate a class using an interface

Consider the code snippet below: interface FirstInterface {} interface SecondInterface {} interface ThirdInterface {} class TheClass { constructor(howdy: FirstInterface) {} } class Foo implements FirstInterface {} class Bar implements SecondInterface ...

How to Vertically Align an HTML Element Inside a Div with Changing Height

Similar Question: Issue with vertical alignment Is there a way to ensure that the <a></a> is always vertically centered within this div, regardless of its size? View example here Thank you! ...

Storing data retrieved from MongoDB into a local array in a MEAN stack

I am currently working on a small application using the MEAN stack. I have saved some user details in MongoDB and now I want to retrieve and store only the email ids in a local array. The fetching part is working well, but I'm facing issues with savin ...

CSS Tutorial: Creating a Dynamic Gradient Bar

I am looking to create a dynamic colored bar with a moving color gradient effect. Without using JavaScript, I want to achieve this effect using CSS 3 properties such as gradients and animations. This is a snippet of what I have tried so far: HTML: <b ...

What are the steps to increase the size of the v-stepper-step in Vuetify?

Is there a way to adjust the size of the icon/step circle in v-stepper? ...

"Trouble with import aliases in a create-react-app project using craco: How to fix it

IMPORTANT UPDATE: Following Stackoverflow guidelines and for the convenience of everyone, I have created a concise reproducible example to showcase the bug in question: https://github.com/shackra/stackoverflow-alias-bug UPDATE 2: Just as an additional no ...

Is there a way to incorporate the router into the observable within the guard?

Is there a way to inject a router into my guard when I have an Observable method returned? I want to implement routing with a redirect to the login page if a certain condition is met: If the result of the isAccessToLobby method is false, then redirect to t ...

Enabling and disabling links in a Bootstrap dropdown menu with dynamic functionality on click

One interesting feature of bootstrap is that it allows users to disable links within its dropdown menu component by simply adding a class="disabled" into the corresponding <li> tag. I am looking to create some Javascript code so that when a user sel ...

Creating grids and dividing them using a combination of CSS, JavaScript, and PHP

I've encountered an interesting challenge while working on a web project and would love some advice on how to tackle it: Within a database, I have a collection of images that I want to display in a grid format. The twist is that higher ranked images ...

HTML border width is set to 100%, but there seems to be an issue with the responsive menu border and icon display

One issue I'm encountering with my website involves the border at the bottom of my navigation bar. Despite trying to adjust the box-sizing property to border-box, I still can't get it to display correctly. My goal is to have the border span 100% ...

Typescript best practice: limiting global variables per file

I found it very useful in jslint to require declaring all used globals at the beginning of a file using the following syntax: /*global console, document */ Is there a similar feature available in Typescript? I managed to disable the implicit availabilit ...

Angular2 Edit form does not have radio button selected according to the value

When editing a form, the radio button does not appear checked according to the value retrieved. I was able to retrieve the last name from the database, but when trying to bind the gender with the radio button, it does not show as checked. <div clas ...

Issue with Angular Material Slide Toggle Binding on Checked Status Not Functioning

It should be a simple task, but I'm struggling to make the checked binding for the slide toggle function properly. (My setup includes angular version 9.1 and material version 9.2.) Here is the HTML snippet: <mat-slide-toggle [checked]="isSlideCh ...

Incorporating jsbi into a TypeScript project while adhering to strict mode

I have been developing a TypeScript library that relies on native BigInts. While it functions perfectly in Chrome, I encountered some issues with Safari. After some research, I stumbled upon the jsbi "polyfill" that seems to solve this problem. Unfortunat ...

CSS: The calc() function does not take into account the bottom padding when used in Firefox and Internet

I am encountering an issue with the calc() function in Firefox 32 and IE 11, where the bottom padding of a div is not being respected. However, this problem does not occur in Chrome and Opera. The main content section should have a fixed height while allo ...

How can one trigger a service method in nestjs through a command?

I am looking to run a service method without relying on API REST - I need to be able to execute it with just one command ...

Validating (Update database with correct email and token)

Authentication (Update database if email and token are accurate) Even when the code is incorrect, it displays "Great Success", but the status does not update in my database. However, if I input the correct code, it shows "Great Success" and updates the s ...