skip to Main Content

Let’s say I have a grid like so

<div style="display:grid; grid-template-columns auto auto;">
    <div>Row 1 Col 1</div><div>Row 1 Col 2</div>
    <div>Row 2 Col 1</div><div>Row 2 Col 2</div>
</div>

Which comes out looking like this:

|Row 1 Col 1|Row 1 Col 2|
|Row 2 Col 1|Row 2 Col 2|

Perfect, just what I want.

Now let’s say I want to refactor my code so that each row is an angular component

<div style="display:grid; grid-template-columns auto auto;">
    <app-row-component row=1></app-row-component>
    <app-row-component row=2></app-row-component>
</div>

And app-row-component looks something like this:

<div>Row {{row}} Col 1</div> <div>Row {{row}} Col 2</div>

Now the styling of the grid no longer works, because angular wraps the content of app-row-component in its own element, and the grid comes out looking like this

|Row 1 Col 1 Row 1 Col 2|Row 2 Col 1 Row 2 Col 2|

Which is not correct.

Is there a way I can remove the wrapping element of the app-row-component so my grid styling still works? Alternatively, is there another way to organize my styling so that I have a grid where each row is a component?

3

Answers


  1. just move the grid styling one level deeper:

    <div style="display:grid; grid-template-columns: auto auto;">
          <div>Row {{row}} Col 1</div> <div>Row {{row}} Col 2</div>
        </div>
    

    Sample stackblitz

    If you want a higher level styling, then use some classes like this:

    <div class="row">
          <div>Row {{row}} Col 1</div> <div>Row {{row}} Col 2</div>
        </div>
    
    <div class="table">
          <app-row-2 [row]="1"></app-row-2>
          <app-row-2 [row]="2"></app-row-2>
        </div>
    

    And a simple selector:

    .table .row {
      display: grid;
      grid-template-columns: auto auto;
    }
    

    Stackblitz is updated.

    I tested gre_gor’s solution, for me it didn’t work. Maybe I do something wrong.

    I have updated the stackblitz with display: contents, it’s working now.

    Login or Signup to reply.
  2. You need to apply display: contents; to the app-row-component.
    This will make CSS grid ignore the element and position its children.

    Add styles: [":host { display: contents; }"] to your component.

    StackBlitz example

    Login or Signup to reply.
  3. It is recommmended but not mandatory to use selectors like app-row-component.

    You can choose a different selector e.g. [app-row-component]:

    <div style="display:grid; grid-template-columns auto auto;">
        <div app-row-component row=1></div>
        <div app-row-component row=2></div>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search