Selecting a Checkbox Resets Entire Form

2 Answers 39 Views
CheckBox DropDownButton DropDownList FormField Forms Grid
Matthew
Top achievements
Rank 1
Matthew asked on 20 Nov 2023, 10:47 PM | edited on 20 Nov 2023, 10:51 PM

Hey everyone, 

Hope this message finds you well. 

I'm creating a grid table with Add/Edit/Delete features. Currently running into a blocker when clicking on a checkbox during an Add procedure. This action completely resets the values from the dropdown menus I've previously selected from. Any ideas as to why this behavior might be occurring? Thanks! 

TS: 

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/other_api/DataService';
import { ErrorHandlerService } from '../../services/error-handler.service';
import { Item } from '../../models/other_api/Item';
import { FormBuilder, FormGroup } from '@angular/forms';
import { SortDescriptor } from "@progress/kendo-data-query";
import { RemoveEvent, SaveEvent } from '@progress/kendo-angular-grid';
import { AnotherService } from '../../services/other_api/AnotherService';
import { DifferentService } from '../../services/other_api/DifferentService';
import { SomeService } from '../../services/other_api/SomeService';

@Component({
  selector: 'app-client',
  templateUrl: './client.component.html',
  styleUrls: ['./client.component.scss'],
})
export class ClientComponent implements OnInit {
  clients: Item[] = [];
  anotherItems: string[] = [];
  differentItems: string[] = [];
  someItems: string[] = [];
  moreItems: string[] = [];
  parentItems: string[] = [];

  constructor(
    private errorHandlerService: ErrorHandlerService,
    private dataService: DataService,
    private anotherService: AnotherService,
    private differentService: DifferentService,
    private someService: SomeService,
    private formBuilder: FormBuilder,
  ) {
    this.createFormGroup = this.createFormGroup.bind(this);
  }

  public formGroup: FormGroup = this.formBuilder.group({
    Id: 0,
    ClientName: '',
    ClientKey: '',
    ParentClientName: '',
    IsParent: false,
    MarketVertical: '',
    Region: '',
    Inactive: false,
    Locale: ''
  });

  public createFormGroup = (args: any): FormGroup => {
    const item = args.isNew ? new Item(0, '', '', '', '', '', false, false, '') : args.dataItem;

    return this.formBuilder.group({
      Id: item.Id,
      ClientName: item.ClientName,
      ClientKey: item.ClientKey,
      ParentClientName: item.ParentClientName,
      IsParent: item.IsParent || false,
      MarketVertical: item.MarketVertical,
      Region: item.Region,
      Inactive: item.Inactive || false,
      Locale: item.Locale
    });
  };

  public sort: SortDescriptor[] = [
    {
      field: "Name",
      dir: "asc",
    },
  ];

  public sortChange(sort: SortDescriptor[]): void {
    this.sort = sort;
    this.getAllClients();
    this.getAnotherItems();
    this.getDifferentItems();
    this.getSomeItems();
    this.getMoreItems();
    this.getParentItems();
  }

  ngOnInit(): void {
    this.getAllClients();
    this.getAnotherItems();
    this.getDifferentItems();
    this.getSomeItems();
    this.getMoreItems();
    this.getParentItems();
  };

  login() {
    //Implementation for login
  };

  showError() {
    this.errorHandlerService.handleError("This is a test error. Stuff is super wrong.");
  }

  getClient(): void {
    this.dataService.get(1).subscribe();
  }

  getAllClients(): void {
    this.dataService.getAll().subscribe((data) => {
      this.clients = data;
    });
  }

  getAnotherItems(): void {
    this.anotherService.getAll().subscribe((data) => {
      this.anotherItems = data.map((anotherItem) => anotherItem.Name);
    });
  }

  getDifferentItems(): void {
    this.differentService.getAll().subscribe((data) => {
      this.differentItems = data.map((differentItem) => differentItem.Description);
    });
  }

  // Similar functions for other services

  saveHandler(args: SaveEvent): void {
    if (args.isNew) {
      this.dataService.create(args.dataItem).subscribe((createdData) => {
        const updateItem = this.clients.filter(element => element.ClientName === createdData.ClientName)[0];
        updateItem.Id = createdData.Id;
      });
    }
    else {
      this.dataService.update(args.formGroup.value).subscribe((updatedData) => {
        const updateItem = this.clients.filter(element => element.Id === updatedData.Id)[0];
        updateItem.ClientName = updatedData.ClientName;
        updateItem.ClientKey = updatedData.ClientKey;
        // Similar updates for other properties
      });
    }
    args.sender.closeRow(args.rowIndex);
  }

  removeHandler(args: RemoveEvent): void {
    this.dataService.delete(args.dataItem).subscribe();
  }
}


------------------------------

HTML:

<link rel="stylesheet" href="https://unpkg.com/@progress/kendo-theme-default/dist/all.css" />
<app-page-layout [workingArea]="body" [footer]="footer">
  <ng-template #body>
    <h1>Clients</h1>
    <kendo-grid [kendoGridReactiveEditing]="createFormGroup"
                [kendoGridBinding]="clients"
                [pageable]="true"
                [sortable]="true"
                [navigable]="true"
                [filterable]="true"
                [sort]="sort"
                (sortChange)="sortChange($event)"
                [pageSize]="10"
                (save)="saveHandler($event)"
                (remove)="removeHandler($event)">
      <ng-template kendoGridToolbarTemplate>
        <button kendoGridAddCommand themeColor="success">Add</button>
      </ng-template>
      <kendo-grid-column field="ClientName" title="Client Name"> </kendo-grid-column>


      <kendo-grid-column [filterable]="false" field="ClientKey" title="Client Key">
        <ng-template kendoGridEditTemplate let-dataItem="dataItem">
          <kendo-dropdownlist [data]="clientKeys" [(ngModel)]="dataItem.ClientKey" name="ClientKey"></kendo-dropdownlist>
        </ng-template>
      </kendo-grid-column>

      <!-- Other columns-->

      <kendo-grid-column [filterable]="true" filter="boolean" field="IsParent" title="Is Parent" editor="boolean">
        <ng-template kendoGridCellTemplate let-dataItem="dataItem">
          <input kendoCheckBox id="isParentCheckbox" type="checkbox" [checked]="dataItem.IsParent" disabled />
        </ng-template>
      </kendo-grid-column>

      <kendo-grid-column [filterable]="true" filter="boolean" field="Inactive" title="Inactive" editor="boolean">
        <ng-template kendoGridCellTemplate let-dataItem="dataItem">
          <input kendoCheckBox id="InactiveCheckbox" type="checkbox" [checked]="dataItem.Inactive" disabled />
        </ng-template>
      </kendo-grid-column>

      <kendo-grid-command-column title="Actions" [width]="220">
        <ng-template kendoGridCellTemplate let-isNew="isNew">
          <button kendoGridEditCommand themeColor="info">
            Edit
          </button>
          <button kendoGridRemoveCommand themeColor="error">Remove</button>
          <button kendoGridSaveCommand themeColor="success">
            {{ isNew ? "Add" : "Update" }}
          </button>
          <button kendoGridCancelCommand themeColor="warning">
            {{ isNew ? "Discard changes" : "Cancel" }}
          </button>
        </ng-template>
      </kendo-grid-command-column>
    </kendo-grid>
  </ng-template>

  <ng-template #footer>
    <app-custom-button [buttonText]="'Login'" aria-label="Login" (onClick)="login()"></app-custom-button>
    <app-custom-button [buttonText]="'Show Error'" aria-label="Show Error" (onClick)="showError()"></app-custom-button>
  </ng-template>
</app-page-layout>

2 Answers, 1 is accepted

Sort by
0
Slavena
Telerik team
answered on 23 Nov 2023, 10:20 AM

Hello Matthew,

Thank you for the provided code snippets.

Upon inspecting the code, it looks like there are multiple additional files, such as services, that may interfere with the component's logic and cause the discrepancy. With that said, I am unable to reproduce the described issue. Could you please provide us with a runnable StackBlitz demo, or an archived project that demonstrates the issue. This would help us further investigate and provide a suitable solution. Thank you for your cooperation in advance.

In the mean time, what I can suggest is checking the following article from our documentation that demonstrates implementing inline editing with the kendoGridReactiveEditing directive:

https://www.telerik.com/kendo-angular-ui-develop/components/grid/editing/editing-directives/#toc-reactive-editing-directive

Feel free to follow the steps from the article and compare both configurations, as this might help finding the root cause of the problem.

For your convenience, I have tweaked the example from the article above, so that it demonstrates rendering a checkbox by utilizing the kendoGridCellTemplate:

https://stackblitz.com/edit/angular-emjdyp-okknej?file=src%2Fapp%2Fapp.component.ts 

I am looking forward to your reply.

Regards,
Slavena
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Kendo family, check out our getting started resources
Matthew
Top achievements
Rank 1
commented on 27 Nov 2023, 04:00 PM

Hi Slavena, 

Thanks for the response.

I guess what my question boils down to is: does Kendo allow dropdown menus (being populated by an API call) to be in the same inline Add/Edit as kendo checkboxes? 

(Haven't been able to find an example in the docs that achieves this functionality)
0
Slavena
Telerik team
answered on 30 Nov 2023, 09:46 AM

Hi Matthew,

The Grid enables you to use templates in order to customize the built-in editing functionality by adding custom validations and input controls:

https://www.telerik.com/kendo-angular-ui/components/grid/editing/custom-editing/ 

With that said, there is no restriction in using both a DropDownList and a CheckBox component as editors. Here is the updated demo that demonstrates such approach:

https://stackblitz.com/edit/angular-gc27nd-vf7dx6?file=src%2Fapp%2Fapp.component.ts

I hope this steers you in the right direction. Let me know if any further assistance is required on this case.

Regards,
Slavena
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Kendo family, check out our getting started resources
Tags
CheckBox DropDownButton DropDownList FormField Forms Grid
Asked by
Matthew
Top achievements
Rank 1
Answers by
Slavena
Telerik team
Share this question
or