Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create the editable primeNG table with Angular forms?

I am trying to create the PrimeNg editable table with angular forms.

app.component.ts (This is minimal reproducable code)

export class AppComponent implements OnInit {
    epForm: FormGroup;
    range: FormArray;

    constructor(private fb: FormBuilder,){
    }
    ngOnInit() {
        this.epForm = new FormGroup({});
        this.epForm.addControl('range', new FormArray([]));
        this.range = <FormArray>this.epForm.get('range');
        this.range.push(
        this.fb.group({
            type: ['X1 Gene']
        })
        );
    }
}

and the html file is

<form [formGroup]="epForm" novalidate>
    <p-table [value]="epForm.controls.range.value" [rows]="10" [responsive]="true">
        <ng-template pTemplate="header">
            <tr> Range </tr>
        </ng-template>
        <ng-template pTemplate="body" let-i="rowIndex">            
            <tr [formGroupName]='i'>
                <td >
                    <input type="text" pInputText formControlName="type" />
                 </td>
             </tr>
        </ng-template>
      </p-table>
</form>

I tried with the above code it is displaying the content, but I cannot able to edit the Input tag. I open the inspect element and i checked it, only the tbody is keyon updating.

I removed the [formgroup]='i' and I checked it in the console I got the following error

 Cannot find control with path: 'range -> type'

The same thing I tried with <table> it is working fine. But with the p-table I am getting this kind of behavior? How can I fix this issue.

StackBlitz

Like the below Image I am getting in the inspect element, with [formGroupName]

enter image description here

like image 770
mkHun Avatar asked Mar 07 '19 06:03

mkHun


1 Answers

I got the answer for my own question, from the primeNg documentation

Performance Tips

When selection is enabled use dataKey to avoid deep checking when comparing objects.

Use rowTrackBy to avoid unnecessary dom operations.

Prefer lazy loading for large datasets.

So I modified my table like

<p-table [value]="epForm.controls.range.value" [rows]="10" [responsive]="true"
[rowTrackBy]="trackByFn">

In the component file I add the following method

trackByFn(index, row) {
    return index;
}
like image 118
mkHun Avatar answered Oct 14 '22 23:10

mkHun