Search code examples
angularangular-flex-layout

Angular: Flex-Layout why are my <div>s not even in width and fxLayoutAlign not working?


I've got an array of 3 elements composed of a title and its respective content. I'm trying to loop over the array to yield a list of s in the DOM which would idealy be the same width and spaced evenly between one another.

So here's my TS with the array:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  list= [
    {title: 'T1 - Lorem ipsum, this a test, just a test', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'},
    {title: 'T2 - Lorem ipsum, this a test, just a test', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'},
    {title: 'T3 - Lorem ipsum, this a test, just a test', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'},
  ];
}

and the corresponding HTML file:

<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="space-evenly">
  <div *ngFor="let el of list">
    <div class="title">{{ el.title }}</div>
    <div class="content">{{ el.content }}</div>
  </div>
</div>

<br>
<br>

<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="space-evenly">
  <div style="background-color: orange">Test1</div>
  <div style="background-color: lightgreen">Test2</div>
  <div style="background-color: lightblue">Test3</div>
</div>

For the sake of the example, you'll see that I have a layed out a second section where there's an example of a list of <div>s properly even in width and evenly spaced in the HTML (section with Test1, 2 and 3).

You'll find a stackblitz here: https://stackblitz.com/edit/angular-3u4sep

Thanks in advance for your help!


Solution

  • If you want different sized children to have the same width, you have to set the same grow property to all of them. You can do this by adding fxFlex="1" (or just fxFlex) to the divs:

    <div *ngFor="let el of list" fxFlex>
      <div class="title">{{ el.title }}</div>
      <div class="content">{{ el.content }}</div>
    </div>
    

    Now all divs have the same grow (and shrink) ratio, so the width will be evenly shared. More info on the fxFlex attribute here.

    Your "TestN" texts have the same width, that's why they're even.