peterc
peterc

Reputation: 7843

How to use CSS grid to have optional third row span two columns inside an Angular *ngFor

What I am trying to do is best described with an example. I have an Angular application, which has list if items (number of items known until runtime), and has two main display columns, and an optional error element.

I would like to lay these columns out so that the first column just takes up what room it needs, and the second can take up the rest (i.e. label / value).

However, I would also kike to optionally display an error under both columns, if there is an error. Here is a full example which is also here.

TypeScript

    constructor() {
            for (let i = 0; i < 12; i++) {
                const item: Item = {
                    label: `Item num${i}`,
                    value: i * 1000,
                    error: undefined
                    //error: i === 0 ? 'Item has a long long long error message' : undefined,
                };
                this.items.push(item);
            }
        }
        

HTML

    <div id="items-container">
        <ng-container *ngFor="let item of items">
            <div class="label-container">
                 <div class="label">{{item.label}}</div>
                 <div class="error">{{item.error}}</div>
            </div>
            <div>{{item.value}}</div>
        </ng-container> 
    </div>
        

CSS

    .error {
        color: red;  
        overflow-y: visible;
        white-space: nowrap;
    }

    #items-container {
        display: grid;
        grid-template-columns: min-content auto;    
        background: lightblue;
    }

    .label {
        white-space: nowrap;
        display: flex;
        justify-items: flex-start;
        align-items: center;
        margin-right: 20px;  
    }

enter image description here

Now, if I add the error, the first column will expand way over.

enter image description here

My question is, is there a way to have the error span the two columns, and not push out the first, eg something like

enter image description here

How can I achieve this?

Upvotes: 0

Views: 606

Answers (1)

Kevin D&#225;vila
Kevin D&#225;vila

Reputation: 26

You can add a class with a grid-column: 1/3 to the error label. This make the error label fill the entire width (two columns)

Upvotes: 1

Related Questions