arundhaj

all that is technology

Progressively adding table rows with Angular

 

I will show how to progressively add new rows to the table as the last row is being edited in Angular

In, app.component.html

<table class="progressive-table">
    <thead>
        <tr>
            <th>KEY</th>
            <th>VALUE</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    <tr *ngFor="let pair of pairs; let idx = index">
        <td>
            <input type="text" [(ngModel)]="pair.Key" (ngModelChange)="pairValueChanged(idx)">
        </td>
        <td>
            <input type="text" [(ngModel)]="pair.Value" (ngModelChange)="pairValueChanged(idx)">
        </td>
        <td>
            <i class="fa fa-times" aria-hidden="true" (click)="deletePair(idx)"></i>
        </td>
    </tr>
    </tbody>
</table>

In, app.component.scss

.progressive-table {
    font-size: 12px;
    width: 100%;
    border-collapse: collapse;

    tr {
        height: 30px;
    }

    th {
        background-color: #eee;
        padding-left: 10px;
    }

    th:last-child {
        width: 5px;
    }

    td, th {
        border: 1px solid lightgray;
        text-align: left;
    }

    input {
        width: 100%;
        padding: 5px;
        border: none;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
    }

    i {
        cursor: pointer;
    }
}

And finally in, app.component.ts

const emptyPair = {'Key': '', 'Value': ''};
let pairs = [{...this.emptyPair}];

pairValueChanged(idx) {
    if (idx === this.pairs.length - 1) {
        this.pairs.push({...this.emptyPair});
    }
}

deletePair(idx) {
    this.pairs.splice(idx, 1);

    if (this.pairs.length === 0) {
        this.pairs.push({...this.emptyPair});
    }
}

Final output looks like this; Output

Hope this helps!

Comments