0

I have a dropdown on each line of a table row and every time I select one option from dropdown the selected value is updated with same value on rest dropdowns:

my html code:

  <p-table....>
 <ng-template pTemplate="body" let-user>
          <tr>
               current user permission: {{user.Permission}}
              <p-dropdown [options]="PermissionOptions" [(ngModel)]="permissionVal" placeholder="change..." optionLabel="name">
              </p-dropdown>
            </td>
          </tr>
 </ng-template>

TS:

interface PermissionType {
  name: string,
}

PermissionOptions1: PermissionType[];
permissionVal1: PermissionType;

constructor()
{
  this.PermissionOptions1 = [
    {name: FolderPermissionEnum.WRITE},
    {name: FolderPermissionEnum.READ},
];

 }

The problem may be spotted on variable permissionVal that receive the selected value from dropdown, and right now that value is common for all dropdowns on the table. If somehow I can change that variable permissionVal to be an array maybe I could solve the problem but I don't know how I can do it or call it on HTML.

Pedro Mendes
  • 99
  • 2
  • 12

1 Answers1

1

Instead of using the two-way binding syntax [(ngModel)], you can split it into [ngModel] property binding and (ngModelChange) event binding syntax, which will give you more control over managing data as per your use case.

Since you have a dropdown on each line of a table row, I assume there would be a way for you to get hold of row number. Suppose row_num represents the row number, then you can have logic as below:

<!-- html file -->
<p-dropdown [options]="PermissionOptions" [ngModel]="permissionValList[row_num]" 
    (ngModelChange)="updatePermissionValList($event, row_num)" 
    placeholder="change..." optionLabel="name">
</p-dropdown>
/* ts file */
permissionValList: PermissionType[] = [];  // or can define type as --> {[key: number]: PermissionType} with default value as {}

updatePermissionValList(event: PermissionType, row_num: number) {
    this.permissionValList[row_num] = event;
}

Edit:

[(ngModel)]="permissionValList[row_num]" should be sufficient in your case, and no need of adding any method for simple assignment, as two-way binding does the same thing.

Siddhant
  • 2,911
  • 2
  • 8
  • 14
  • I didn't tested your solution yet , but sounds promising. I just added let-rowIndex="rowIndex" on ng-template and called on permissionVal[rowIndex]. And finally i have initialized the permissionVal array on constructor so all is working fine now. But i may also test with your solution too, thanks. – Pedro Mendes Jan 11 '22 at 18:55
  • @Pedro Actually you may not even need to split `[(ngModel)]` syntax if it's simple assignment as I have shown in example. That would be required if you need to handle some other logic. So whatever you have done, sounds good. – Siddhant Jan 11 '22 at 19:02