Adjusting the width of row items in Angular by modifying the CSS styles

I am envisioning a horizontal bar with items that are all the same width and evenly spaced apart. They can expand vertically as needed.

Check out the updated version here on StackBlitz

https://i.sstatic.net/MFfXd.png

Issue: I am struggling to automatically set the width of the row elements. Currently, I have hardcoded a width value: width:200px, but I want the width to be determined by the number of elements per row.

Attempted Solution: I tried using elementRef in the Horizontile component to retrieve the width of each element:

currentWidth:number;
constructor(private el:ElementRef) {}

  ngAfterViewInit(): void {
    this.currentWidth=this.el.nativeElement.offsetWidth;}

However, this approach did not yield the desired result, and I believe it creates unnecessary coupling between components.

Upon further inspection, I discovered that setting width:inherit; in the CSS of the individual tile component allows me to dynamically adjust the width from the horizontal list component:

<app-tile [style.width.px]="0.9*currentWidth/nDisplayedTiles" [tile]="item"></app-tile>

Unfortunately, since the currentWidth is initially zero, this solution does not work as anticipated.

I also attempted to use percentages for the width calculation, but the inherits CSS property retains the percentage value instead of adjusting accordingly. Why does the app-tile styling not respond to changes when inherits is not utilized? Additionally, applying ViewEncapsulation did not provide the desired outcome either.

Although this may seem like a minor issue, I feel like I might be overlooking something simple. Any insights or suggestions would be greatly appreciated.

Answer №1

To retrieve the width of each cell using the offsetParent property, you can create a method that calculates and returns the value for each cell. This method can then be called in the [style.width.px] attribute. Here is an example of how this can be implemented.

The HTMLElement.offsetParent property provides a reference to the closest positioned ancestor element in the containment hierarchy.

Check out this stackblitz link for more information.

ngAfterViewInit(): void {
    // Added setTimeout function to prevent ExpressionChangedAfterItHasBeenCheckedError
    setTimeout(() => { 
      this.currentWidth = this.el.nativeElement.offsetParent.clientWidth;
    });
}

getWidth(): number{
     let width: number = 0;

     // Adjust multiplier as needed for better cell display
     let multiplier = 0.7;

     width = (this.currentWidth * multiplier) / this.ndisplayTiles;
     width = Math.round(width);

     return width;
}

<app-tile [class]="'layout-tile'" [tile]="item"  [style.width.px]="getWidth()">
</app-tile>

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

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Ellipsis malfunctioning in text overflow

It is known that the display type table-cell does not work with text-overflow ellipsis. However, this is where my issue lies. I am dealing with a file input control that appears like this: <div class="ui-select form-input" style="display:inline-block; ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Align navigation items in the center of the navigation container

I've been grappling with aligning the content of a nav-item inside a nav container in my project. I'm unable to apply a margin on the ul>li items as it doesn't adjust properly on different resolutions. I've tried using percentages, b ...

Encountering difficulty in fetching data from a service with ng-select

Currently, I am utilizing ng-select for a form that allows users to search for activities to add. The ng-select component triggers a function whenever something is typed into the field. This function then calls a service that fetches an array of activities ...

The nested ThemeProvider takes priority over the theme's style definitions

Is there a way to render a component and then apply additional rendering using useEffects in React? The issue I am facing is that when I have a component with a specific theme, each useEffect call ends up overriding the style of the original component wit ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

Attempting to create an interactive stepper within a material dialog using reactive forms for a versatile "smart" helper feature

Currently, I am working on developing an assistant that can display different steps based on the data it receives. This flexibility will allow me to use the assistant for various user types, each requiring a unique set of steps. For example, registration m ...

Failed to install Firebase due to an error

I am attempting to utilize firebase as my database. After running npm install angularfire2 firebase --save, I encountered the following error stack: C:\Users\Batbrain\Desktop\Angular5\GitHub\travelapp>npm install a ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

What is the best way to implement media queries in a column layout for a responsive webpage?

My goal is to display a picture below the navbar when the window size becomes small or in mobile mode, followed by my name and other details. However, I am having trouble understanding how to implement this using media queries. DESKTOP PREVIEW https://i. ...

retrieving a single object from $resource by passing a non-ID parameter

I am utilizing $resource to retrieve an array of objects. The method I am invoking is as follows: fetchTeamResource(): ng.resource.IResourceClass<ITeamResource> { return this.$resource("/api/Teams:teamId"); } Below is how I am i ...

I have noticed that the Javascript code is being loaded prior to the completion of my HTML/CSS page for some unknown

I am completely new to the world of web development. I'm encountering an issue where my JavaScript code (specifically alerts) is loading before my HTML/CSS page has fully loaded. I've been using sample alerts to test this out, and ideally, they s ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Using JQuery to reverse the action of hiding an image

Having some trouble with my Javascript and JQuery skills, so bear with me. I've set up a gallery of images where users can drag and drop them into a designated drop zone. Everything works fine when dragging an image from the gallery to the drop zone a ...

The header and footer elements must be included along with a main div to house the content on the webpage

I am currently working on building a website using HTML and CSS. I would like to create an index.php file that calls all the different parts of the page. For example, I want to include the header and footer, and also have the ability to replace content wit ...

In TypeScript/Angular, what is the best way to share model variables between a Service class and a controller class?

Is there a way for the Controller and Service classes to access the same model without explicitly passing it? For example: Controller Class : import { SearchModel } from "../../models/SearchModel"; import { SearchService } from "../../components/SearchS ...

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

Leverage the power of rxjs to categorize and organize JSON data within an

I am in need of reformatting my data to work with nested ngFor loops. My desired format is as follows: this.groupedCities = [ { label: 'Germany', value: 'de', items: [ {label: 'Berlin', value: 'Berlin ...