Home > Mobile >  Preselect checkboxes in primeng table
Preselect checkboxes in primeng table

Time:11-10

I have a requirement to preselect first 20 rows in primeng table I have tried the following, but it gives an error can't bind to 'checked' since it isn't a known property of p-checkbox I have tried replacing with ngModel as written in posts but to no avail


  <ng-template pTemplate="body" let-transaction let-expanded="expanded">

        <tr [pSelectableRow]="transaction">

            <td [hidden]='!isMultiSign'><p-tableCheckbox [checked]='isSelected(transaction)'

                 [value]='transaction' (onChange)='check(transaction)' [pSelectableRow]='transaction'>

            </p-tableCheckbox></td>

CodePudding user response:

The selection is defined by the selection value of the table. I edited primeng's example for you to show:

html

<p-toast></p-toast>

<div >
  <h5>Checkbox Selection</h5>
  <p>
    Multiple selection can also be handled using checkboxes by enabling the
    selectionMode property of column as "multiple".
  </p>

  <!-- see the selection binding here -->
  <p-table [value]="products" [(selection)]="selectedProducts3" dataKey="code">
    <ng-template pTemplate="header">
      <tr>
        <th style="width: 3rem">
          <p-tableHeaderCheckbox></p-tableHeaderCheckbox>
        </th>
        <th>Code</th>
        <th>Name</th>
        <th>Category</th>
        <th>Quantity</th>
      </tr>
    </ng-template>
    <ng-template pTemplate="body" let-product>
      <tr>
        <td>
          <p-tableCheckbox [value]="product"></p-tableCheckbox>
        </td>
        <td>{{ product.code }}</td>
        <td>{{ product.name }}</td>
        <td>{{ product.category }}</td>
        <td>{{ product.quantity }}</td>
      </tr>
    </ng-template>
  </p-table>
</div>

Ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [MessageService],
})
export class AppComponent {
  products: Product[];

  selectedProducts3: Product[];

  constructor(
    private productService: ProductService,
    private messageService: MessageService
  ) {}

  ngOnInit() {
    this.productService.getProductsSmall().then((data) => {
      this.products = data;
      // selects the first 2
      this.selectedProducts3 = data.slice(0, 2);
    });
  }

  selectProduct(product: Product) {
    this.messageService.add({
      severity: 'info',
      summary: 'Product Selected',
      detail: product.name,
    });
  }

  onRowSelect(event) {
    this.messageService.add({
      severity: 'info',
      summary: 'Product Selected',
      detail: event.data.name,
    });
  }

  onRowUnselect(event) {
    this.messageService.add({
      severity: 'info',
      summary: 'Product Unselected',
      detail: event.data.name,
    });
  }
}
  • Related