Angular primeNg dropdown
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.
Solution 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.