primengangular9primeng-turbotableprimeng-dropdownsp-table

p-dropdown in p-table dynamic rows PrimeNG - version 9 - Stackblitz added


My requirement is to have dropdowns in each row of two columns of grid as below:

enter image description here

Here is stackblitz for my problem: https://stackblitz.com/edit/angular9-primeng9

User can select values for each row and save. I am able to fetch data from data source using service and initialize dropdown options in subscribe of observable. However, I am not able to set the selected item of each row on page load to display pre-existing rows (I think problem of setting up [(ngModel)]).

Also, I need to add a plus button which would add a new row to this table and result should be saved to database on save action. Any guidance / lead to address this issue would be of great help.

Below is HTML code I am using:

<p-table [columns]="cols" [value]="rows">
            <ng-template pTemplate="header" let-columns>
                <tr>
                    <th *ngFor="let col of columns">
                        {{col.header}}
                    </th>
                </tr>
            </ng-template>
            <ng-template pTemplate="body" let-rowData let-columns="columns">
                <tr>                    
                    <td>
                        <p-dropdown [options]="DropdownSource" [(ngModel)]="rowData.AAttribute" placeholder="Select"
                            [showClear]="true"></p-dropdown>
                    </td>
                    <td>
                        <p-dropdown [options]="DropdownSource" [(ngModel)]="rowData.BAttribute" placeholder="Select"
                             [showClear]="true"></p-dropdown>
                    </td>
                </tr>
            </ng-template>
        </p-table>

and in component (subscribe in onchanges):

this.cols = [
                { "field": "field_0", "header": "A Attribute" },
                { "field": "field_1", "header": "B Attribute" }
              ];

this.rows = [{ "AAttribute": "Data3", "BAttribute": "DataC" },
          { "AAttribute": "Data5", "BAttribute": "DataE" }];


this.DropdownSource= [
            { "AAttribute": "Data1", "BAttribute": "DataA" },
            { "AAttribute": "Data2", "BAttribute": "DataB" },
            { "AAttribute": "Data3", "BAttribute": "DataC" },
            { "AAttribute": "Data4", "BAttribute": "DataD" },
            { "AAttribute": "Data5", "BAttribute": "DataE" },
            { "AAttribute": "Data6", "BAttribute": "DataF" }]

Solution

  • ngmodel expects object from the array.

    refer below stackblitz https://stackblitz.com/edit/angular9-primeng9-dgxsjj

    this.mappingRows = [{ "targetCol": "DataF", "SourceCol": this.sourceAttributes.find(p=>p.label === "Data3") },
                  { "targetCol": this.targetAttributes[3], "SourceCol": "Data6" },
                  { "targetCol": "DataC", "SourceCol": "Data1" }];