2
votes

I have a primeng pdatatable with a p-dropdown, I want to select an item from the p-dropdown and add it to the p-datatable(empty in the begining) with the onChange event, it shows the added items with ngFor but it doesn't with p-datatable, what should I change? Thanks

PS. I'm using angular 2

In the component:

         ...
    public existencias: Existencia[] = [];
    public ex_pd: Existencia[] = [];
    public medicamentos: SelectItem[];
              ...
    private getAllExistencias() {
            this.existenciaService
                .getAllExistencias()
                .subscribe(
                data => {
                    this.existencias = data;
                    this.medicamentos = [];
                    for (let i = 0; i < this.existencias.length; i++)
                    {
                        this.medicamentos.push({ label: this.existencias[i].medicamento.nombre , value: this.existencias[i].medicamento.nombre });
                    }
                },
                error => console.log(error),
                () => console.log('Complete')
                );
        }

 public addMedicamento(medic: string) {//

         let e = this.existencias.filter(e => e.medicamento.nombre == medic);
         this.ex_pd.push(e[0]);
     }

in the template:

this way it works:

<tr *ngFor="let pd of ex_pd; let i = index">

but this way nothing is shown in the p-datatable:

<p-dataTable [value]="ex_pd" ...>
        <p-header>Listado de Medicamentos ...</p-header>
        <p-column field="medicamento.nombre" header="Nombre" ... >
            <ng-template pTemplate="filter" let-col>
                <p-dropdown [options]="medicamentos" [style]="{'width':'100%'}" (onChange)="addMedicamento($event.value)" styleClass="ui-column-filter"></p-dropdown>
            </ng-template>
        </p-column>
     <p-column field="medicamento.cantidad" header="Cantidad" ... >
        ...
2

2 Answers

1
votes

Yes, what he said it's correct, but probably the best way is to follow immutable principles!

That means you have to recreate your array/object all the time. How to do that easily?

//use spread operator
newArr = [...oldArr];

//use Object.Assign
newArr = Object.assign([], oldArr)
0
votes

Make sure the "immutable" property is set to false. This property is defaulted to true and it caused an error for me similar to what you are talking about.

<p-dataTable [immutable]="false" ...>

https://www.primefaces.org/primeng/#/datatable