Как создать редактируемую таблицу PrimeNG с угловыми формами? - PullRequest
3 голосов
/ 07 марта 2019

Я пытаюсь создать редактируемую таблицу PrimeNg с угловыми формами.

app.component.ts (это минимальный воспроизводимый код)

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']
        })
        );
    }
}

и HTML-файл

<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>

Я пытался с помощью приведенного выше кода отображать содержимое, но я не могу редактировать тег ввода. Я открываю элемент проверки и проверяю его, только ключ tbody обновляется.

Я удалил [formgroup]='i' и проверил его в консоли. Я получил следующую ошибку

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

То же самое, что я пробовал с <table>, работает нормально. Но с помощью p-таблицы у меня такое поведение? Как я могу исправить эту проблему.

StackBlitz

Как показано на рисунке ниже, я получаю в элементе проверки, с [formGroupName]

enter image description here

Ответы [ 2 ]

1 голос
/ 12 марта 2019

Я получил ответ на свой собственный вопрос из документации PrimeNg

Советы по повышению производительности

При выбореВключено использование dataKey, чтобы избежать глубокой проверки при сравнении объектов.

Используйте rowTrackBy, чтобы избежать ненужных операций с dom.

Предпочитать отложенную загрузку для больших наборов данных.

Поэтому я изменил свою таблицу следующим образом:

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

В файле компонента я добавил следующий метод

trackByFn(index, row) {
    return index;
}
0 голосов
/ 11 марта 2019
Use Like this as mentioned in Doc 

при https://www.primefaces.org/primeng/#/table/edit

Html 
    <p-table [value]="cars">
        <ng-template pTemplate="header">
            <tr>
                <th>Vin</th>
                <th>Year</th>
                <th>Brand</th>
                <th>Color</th>
            </tr>
        </ng-template>
        <ng-template pTemplate="body" let-rowData>
            <tr>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.vin">
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.vin}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.year" required>
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.year}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <p-dropdown [options]="brands" [(ngModel)]="rowData.brand" [style]="{'width':'100%'}"></p-dropdown>
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.brand}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.color">
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.color}}
                        </ng-template>
                    </p-cellEditor>
                </td>
            </tr>
        </ng-template>
    </p-table>

    <h3>Row Editing</h3>
    <p-table [value]="cars2" dataKey="vin">
        <ng-template pTemplate="header">
            <tr>
                <th>Vin</th>
                <th>Year</th>
                <th>Brand</th>
                <th>Color</th>
                <th style="width:8em"></th>
            </tr>
        </ng-template>
        <ng-template pTemplate="body" let-rowData let-editing="editing" let-ri="rowIndex">
            <tr [pEditableRow]="rowData">
                <td>
                    {{rowData.vin}}
                </td>
                <td>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.year" required>
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.year}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <p-dropdown [options]="brands" [(ngModel)]="rowData.brand" [style]="{'width':'100%'}"></p-dropdown>
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.brand}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.color">
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.color}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td style="text-align:center">
                    <button *ngIf="!editing" pButton type="button" pInitEditableRow icon="pi pi-pencil" class="ui-button-info" (click)="onRowEditInit(rowData)"></button>
                    <button *ngIf="editing" pButton type="button" pSaveEditableRow icon="pi pi-check" class="ui-button-success" style="margin-right: .5em" (click)="onRowEditSave(rowData)"></button>
                    <button *ngIf="editing" pButton type="button" pCancelEditableRow icon="pi pi-times" class="ui-button-danger" (click)="onRowEditCancel(rowData, ri)"></button>
                </td>
            </tr>
        </ng-template>
    </p-table>


Component be like .

enter code here

    export class TableEditDemo implements OnInit {

        cars1: Car[];

        cars2: Car[];

        brands: SelectItem[];

        clonedCars: { [s: string]: Car; } = {};

        constructor(private carService: CarService) { }

        ngOnInit() {
            this.carService.getCarsSmall().then(cars => this.cars1 = cars);
            this.carService.getCarsSmall().then(cars => this.cars2 = cars);

            this.brands = [
                {label: 'Audi', value: 'Audi'},
                {label: 'BMW', value: 'BMW'},
                {label: 'Fiat', value: 'Fiat'},
                {label: 'Ford', value: 'Ford'},
                {label: 'Honda', value: 'Honda'},
                {label: 'Jaguar', value: 'Jaguar'},
                {label: 'Mercedes', value: 'Mercedes'},
                {label: 'Renault', value: 'Renault'},
                {label: 'VW', value: 'VW'},
                {label: 'Volvo', value: 'Volvo'`enter code here`}
            ];
        }

        onRowEditInit(car: Car) {
            this.clonedCars[car.vin] = {...car};
        }

        onRowEditSave(car: Car) {
            if (car.year > 0) {
                delete this.clonedCars[car.vin];
                this.messageService.add({severity:'success', summary: 'Success', detail:'Car is updated'});
            }
            else {
                this.messageService.add({severity:'error', summary: 'Error', detail:'Year is required'});
            }
        }

        onRowEditCancel(car: Car, index: number) {
            this.cars2[index] = this.clonedCars[car.vin];
            delete this.clonedCars[car.vin];
        }

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...