dataTable Primeng和Angular 4中的Selected Item查找索引-1

时间:2017-05-04 17:00:28

标签: angular primeng

大家好我想选择要删除和编辑的项目,我不使用Prime的CRUD dataTable我使用ng-template和列

所以我的代码就像这样

 <p-dataTable [value]="users" selectionMode="single" [(selection)]="selectedUser" (onRowSelect)="onRowSelect($event)" [paginator]="true" rows="15" [responsive]="true">
    <p-column field="nom" header="Nom" [sortable]="true"></p-column>
    <p-column field="email" header="Email" [sortable]="true"></p-column>
    <p-column field="brand" header="Modfier" [sortable]="true">
            <ng-template let-col let-user="rowData" pTemplate="body">
                <button type="button" pButton (click)="editUser(user)" tooltipPosition="top" icon="fa fa-pencil"></button>
            </ng-template>

    </p-column>
    <p-column field="color" header="Supprimer" [sortable]="true">
        <ng-template let-col let-user="rowData" pTemplate="body">
            <button type="button" pButton (click)="deleteUser(user)" tooltipPosition="top" icon=" fa fa-trash"></button>
        </ng-template>
    </p-column>
</p-dataTable>

当我点击删除用户时我首先需要索引,所以我在组件中调用此函数

findSelectedUserIndex(): number {
        return this.users.indexOf(this.selectedUser);
 }

但是当我点击deleteUser

 deleteUser(user:User){
        console.log(user);
        console.log("here",this.findSelectedUserIndex());
    }

这个函数来获取行选择

 onRowSelect(event) {
        this.newUser = false;
        this.user = this.cloneUser(event.data);
        this.displayDialog = true;
    }

    cloneUser(c: User): User {
        let usr = new User();
        for(let prop in c) {
            usr[prop] = c[prop];
        }
        return usr;
    }

我得到所有数据的用户,但是在this.findSelectedUserIndex()中我得到-1
所以任何人都可以帮我解决这个问题,谢谢你

1 个答案:

答案 0 :(得分:1)

rowIndex添加到您的ng-template,并在点击删除时将其传递给

<p-column field="color" header="Supprimer" [sortable]="true">
        <ng-template let-col let-user="rowData" let-i="rowIndex" pTemplate="body">
            <button type="button" pButton (click)="deleteUser(user,i)" tooltipPosition="top" icon=" fa fa-trash"></button>
        </ng-template>
    </p-column>

你的方法应该是

deleteUser(user:User,index:number){
        console.log(user);
        console.log("here",index);
    }