Home > Software design >  Dynamically set css text-overflow width based on other dom element widths
Dynamically set css text-overflow width based on other dom element widths

Time:03-29

I have a mat-list in an Angular component like below (food-list.component.html)

sample mat list UI

<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} ><small>{{food.label}}</small></p>
          <p matLine [ngStyle]="{width: foodLabelWidth} ><small>{{food.type}}</small></p>
       </mat-list-item>
    </ng-container>
</mat-list>

And in CSS file (food-list.component.scss)

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

As example in a desktop view mat list item width 100px and, MatIconWidth is 5px. and in mobile view mat list item width 50px and, MatIconWidth is 5px. I want to set text overflow width according to the space that left.

for example, in food-list.component.ts I want to do something like this.

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

to make it happen I want to get DOM element width of

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

Which lies inside a NgFor loop. Is there a way to achieve this?

CodePudding user response:

Use CSS break points , I think that can help you to do the project. Read this >> :Common breakpoints for media queries on a responsive site or W3Schools:https://www.w3schools.com/howto/howto_css_media_query_breakpoints.asp

CodePudding user response:

So I could use flex design to make it work !! https://css-tricks.com/snippets/css/a-guide-to-flexbox/

in html file

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

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;
}
  • Related