Adjust the width of text overflow in CSS dynamically by considering the widths of other elements in the DOM

Within my Angular component, I have a mat-list structured like this in the food-list.component.html file:

<mat-list id="site-list">
     <ng-container *cdkVirtualFor="let food of foods">
        <mat-list-item  id="food-{{food.id}}">
          <mat-icon *ngIf="showFoodIcon" color="warn">not_listed_location</mat-icon>
          <p matLine [ngStyle]="{width: foodLabelWidth} class="overflowText"><small>{{food.label}}</small></p>
          <p matLine [ngStyle]="{width: foodLabelWidth} class="overflowText"><small>{{food.type}}</small></p>
       </mat-list-item>
    </ng-container>
</mat-list>

In the corresponding CSS file (food-list.component.scss), I have defined the following styling:

p.overflowText {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

My goal is to dynamically set the width for the text overflow based on the available space. For instance, in desktop view, the mat list item width is 100px and the MatIconWidth is 5px. In mobile view, the mat list item width is 50px with the same MatIconWidth of 5px.

To achieve this, I plan to calculate the text overflow width in the food-list.component.ts file as follows:

ngOnInit(): void {
   this.foodLabelWidth = matListItemWidth - MatIconWidth;
}

However, in order to accurately calculate this width, I need to access the DOM element width of the following icon:

    <mat-icon *ngIf="showFoodIcon" color="warn">not_listed_location</mat-icon>

This icon is nested inside a NgFor loop. Is there a way to accomplish this?

Answer №1

Utilizing flex design was the key to getting it to work effectively! Explore more about using flexbox in CSS here

This code snippet belongs in an HTML file:

<mat-list id="site-list">
     <ng-container *cdkVirtualFor="let food of foods">
        <mat-list-item  id="food-{{food.id}}">
          <div class="flex-row w-100">
              <div class="flex-row">
                <mat-icon *ngIf="showFoodIcon" color="warn">not_listed_location</mat-icon>
              </div>
              <div class="food-title">
                  <p matLine class="overflowText"><small>{{food.label}}</small></p>
                  <p matLine class="overflowText"><small>{{food.type}}</small></p>
              </div>
          </div>
       </mat-list-item>
    </ng-container>
</mat-list>

And this part goes into a SCSS file:

::ng-deep .cdk-virtual-scroll-content-wrapper {
  max-width: 100%
}

.flex-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overflow {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.food-title {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

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

AngularJS is receiving an array of null inputs

I have a form where data from my DB is displayed through WebApi. One of the controls will contain an array of values. There is a scenario where the user can edit and save it using the PUT function. Controller : $scope.Put= function () { $scope.i ...

Transferring a header across a series of interconnected services

I have a script that calls two services, combines their results, and displays them to the user. The services are: Service 1 (hello) and Service 2 (world), resulting in "Hello world". I want to include an ID in the headers to track the route of the calls. ...

I am struggling to get the pop-up to close using the current code. I suspect that the issue might be related to the variable I was previously using in WordPress. I have made changes but the pop-up

While delving deeper into the realm of Javascript, I encountered a stumbling block with a single popup intended for the main page of a WordPress website I am constructing. Despite my attempts to modify the code's variables, they seem unyielding. Surpr ...

How can I identify when a browser window is maximized using JavaScript or CSS?

I am currently working on a dashboard designed for static display on large monitors or TVs for clients. My main goal is to implement CSS styling, specifically a snap-scroll feature, but only when the display is in 'fullscreen' or 'maximized& ...

Guide to automatically refreshing a page every 30 seconds for a total of 5 times

Is there a way to automatically refresh a page 5 times with a delay of 30 seconds between each refresh without causing the entire page to reload? I'm trying to avoid using the document.location.reload() JavaScript function as it reloads the entire pag ...

Tips for personalizing my XLSX file with TypeScript and Angular?

My JSON data includes: { "cost": 852.14, "gross":741.85, "net": 213.00, "quantity":30, "missing": 20, "waiting":5 } Here is the code I am using: const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.reportPayment, { ...

Checking for correct HTML tags using JavaScript

Looking to validate some input in javascript and confirm if it is a valid HTML tag. Any straightforward methods with JQuery for this task? If not, any suggestions on how to achieve this using Regex? Thank you! ...

I am facing issues with the functionality of the "facebook.php" file

As a newcomer to the realm of PHP and Facebook integration, I am faced with a challenge. I am attempting to link my website to my Facebook page in order to access the content, but unfortunately, a basic program I created does not seem to be functioning pro ...

Can System.import in webpack be configured to utilize ajax for progress events?

Recently upgraded to webpack 2, and I've successfully set it up to automatically generate chunks based on System.import calls. It's pretty cool! However, I'm currently loading the initial chunk through an ajax call in order to monitor progr ...

Uniform Height for Several Selectors

I came across a script on Codepen created by RogerHN and decided to customize it for a project I'm currently working on: https://codepen.io/RogerHN/pen/YNrpVa The modification I made involved changing the selector: var matchHeight = function ...

What is the best way to showcase 100 json data entries within an HTML document?

Starting from scratch with html, css, and javascript, I've embarked on a basic learning project. Within this project, I plan to create two main pages: a list page and a detail page. The list page will showcase posts on the html screen, featuring only ...

The issue with loading pages in jQuery Mobile AJAX is not being resolved

echo '<script> function ' . $row['idname'] . 'Click(){ $( "#flip-' . $row['idname'] . '" ).flipswitch( "disable" ); var isOff = document.getElementById("flip-' . $row['idname& ...

Adding an arrow between two divs in html and css

I am looking to add an arrow between two divs. Here is an example image for reference: https://i.sstatic.net/Sl5A8.png This is my current setup: <style> .link{ font-size: 14px; margin-bottom: 10px; } ...

The type x cannot be assigned to the parameter '{ x: any; }'

Currently learning Angular and Typescript but encountering an error. It seems to be related to specifying the type, but I'm unsure of the exact issue. Still new at this, so any guidance is appreciated! src/app/shopping-list-new/shopping-edit/shopp ...

Bidirectional Data Flow with rxjs in Angular

After adapting an Angular template and component from Angular Material's dashboard schematic, I wanted to manipulate the properties on the "cards" object using events and two-way data binding. Initially, it seemed like two-way data binding was working ...

The functionality of the offcanvas button is not working correctly

I am currently utilizing the newest Bootstrap version of Offcanvas. Interestingly, there seems to be an issue with the close button functionality. When I click the "Add to Cart" button, the offcanvas displays properly. However, the "Add to Cart" button its ...

Guide to automatically select an option in a dropdown menu using a URL

I am currently working on implementing a dropdown select menu that helps filter an HTML table based on the user's choice. My goal is to utilize the URL of the page to automatically pre-select an option in the dropdown. For instance, if the URL looks l ...

Jest test failing due to issues with a stateful React component containing an asynchronous function

I'm currently going through a Jest testing tutorial on Pluralsight that can be found here. Even though I have written the code exactly like the author, my test is not passing for some reason. Link to my Pull request on the author's repo: https:/ ...

I can't figure out why my code is only returning the else statement and an undefined value instead of the totalBasketballScore

I was confident that my code was correct, but I am encountering an issue when trying to calculate basketball scores based on free throws, 2 pointers, and 3 pointers. Whenever I console.log the totalBasketballScore, the output is 'All entries must be n ...

What is the best way to format the incoming data to display as HTML code?

My textarea has a v-model called content where input text is assigned to content.description. Now, I need to transfer this information to another element, specifically a div. The challenge lies in the fact that if my textarea includes HTML code, I want it ...