Show Add New Row always on the grid in Template Editing Mode

I have created a grid component that can be edited in the row itself. I have used Normal as the edit type and it is created with Template-Driven Form. Now I need to make it always editable. need to show an editable row on top of the grid.so I have set showAddNewRow as true in the editSetting property of the grid. then the editable row is showing but I can edit this customer name column only. other syncfusion date picker, numeric text box, and dropdown-list are not showing. those cells are showing empty. my code is following.

my app.component.html

<style>

.control-section{

    margin-top: 100px;

}

</style>

<div class="control-section">

    <ejs-grid [dataSource]='data' allowPaging='true' [pageSettings]='pageSettings' [allowSorting]='true' [editSettings]='editSettings' [toolbar]='toolbar' (actionBegin)='actionBegin($event)' (actionComplete)='actionComplete($event)'>

        <e-columns>

            <e-column field='OrderID' headerText='Order ID' width='120' textAlign='Right' [isPrimaryKey]='true'></e-column>

            <e-column field='CustomerName' headerText='Customer Name' width='120'></e-column>

            <e-column field='Freight' headerText='Freight' width='120' format='C2' textAlign='Right'></e-column>

            <e-column field='OrderDate' headerText='Order Date' width='130' format='yMd' textAlign='Right'></e-column>

            <e-column field='ShipCountry' headerText='Ship Country' width='150'></e-column>

        </e-columns>

        <ng-template #editSettingsTemplate let-data>

            <div ngForm #orderForm="ngForm">

                <table class="e-table e-inline-edit" cellspacing="0.25">

                    <colgroup>

                            <col style="width: 120px;">

                            <col style="width: 120px;">

                            <col style="width: 120px;">

                            <col style="width: 130px;">

                            <col style="width: 150px;">

                    </colgroup>

                    <tbody>

                        <tr>

                            <td style="text-align: right" class='e-rowcell'>

                                <div class="e-input-group" [ngClass]= "{'e-disabled': !data.isAdd}">

                                    <input class="e-input e-field" [(ngModel)]="orderData.OrderID" required [attr.disabled]="!data.isAdd ? '' : null" name='OrderID' type="text" (focus)="focusIn($event.target)"

                                        (blur)="focusOut($event.target)" #OrderID style="text-align: right" />

                                </div>

                            </td>

                            <td class='e-rowcell'>

                                <div class="e-input-group">

                                    <input class="e-input e-field" name='CustomerName' [(ngModel)]="orderData.CustomerName" required type="text" (focus)="focusIn($event.target)"

                                        (blur)="focusOut($event.target)" #CustomerName />

                                </div>

                            </td>

                            <td style="text-align: right" class='e-rowcell'>

                                <ejs-numerictextbox name="Freight" id="Freight" [(ngModel)]="orderData.Freight" floatLabelType='Never'></ejs-numerictextbox>

                            </td>

                            <td style="text-align: right" class='e-rowcell'>

                                <ejs-datepicker id="OrderDate" name="OrderDate" [(ngModel)]="orderData.OrderDate" floatLabelType='Never'></ejs-datepicker>

                            </td>

                            <td class='e-rowcell'>

                                <ejs-dropdownlist id="ShipCountry" name="ShipCountry" [(ngModel)]="orderData.ShipCountry" [dataSource]='shipCountryDistinctData' [fields]="{text: 'ShipCountry', value: 'ShipCountry' }" popupHeight='300px' floatLabelType='Never'></ejs-dropdownlist>

                            </td>

                        </tr>

                    </tbody>

                </table>

            </div>

        </ng-template>

    </ejs-grid>


</div>

app.component.ts 

@Component({

    selector: 'app-root',

    templateUrl: 'app.component.html',

    providers: [ToolbarService, EditService, PageService, SortService],

    standalone: true,

    imports: [GridModule, ReactiveFormsModule, FormsModule, NgClass, NumericTextBoxModule, DatePickerModule, DropDownListModule]

})

export class AppComponent {

    public data: Object[];

    public editSettings: Object;

    public toolbar: string[];

    public pageSettings: Object;

    public shipCityDistinctData: Object[];

    public shipCountryDistinctData: Object[];

    public orderData: IOrderModel;

    @ViewChild('orderForm')

    public orderForm: FormGroup;

    @ViewChild('OrderID')

    public orderID: ElementRef;

    @ViewChild('CustomerName')

    public customerName: ElementRef;


    public ngOnInit(): void {

        this.data = orderDetails;

        this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true,showAddNewRow :true, mode: 'Normal' };

        this.toolbar = ['Add', 'Edit', 'Delete', 'Update', 'Cancel'];

        this.pageSettings = { pageCount: 5};

        this.shipCityDistinctData = DataUtil.distinct(orderDetails, 'ShipCity', true);

        this.shipCountryDistinctData = DataUtil.distinct(orderDetails, 'ShipCountry', true );

    }


    actionBegin(args: SaveEventArgs): void {

        if (args.requestType === 'beginEdit' || args.requestType === 'add') {

            this.orderData = Object.assign({}, args.rowData);

        }

        if (args.requestType === 'save') {

            if (this.orderForm.valid) {

                args.data = this.orderData;

            } else {

                args.cancel = true;

            }

        }

    }


    actionComplete(args: DialogEditEventArgs): void {

        if (args.requestType === 'beginEdit' || args.requestType === 'add') {

            // Set initail Focus

            if (args.requestType === 'beginEdit') {

                (args.form.elements.namedItem('CustomerName') as HTMLInputElement).focus();

            } else if (args.requestType === 'add') {

                (args.form.elements.namedItem('OrderID') as HTMLInputElement).focus();

            }


        }

    }


    public focusIn(target: HTMLElement): void {

        target.parentElement.classList.add('e-input-focus');

    }


    public focusOut(target: HTMLElement): void {

        target.parentElement.classList.remove('e-input-focus');

    }


}


export interface IOrderModel {

    OrderID?: number;

    CustomerName?: string;

    ShipCity?: string;

    OrderDate?: Date;

    Freight?: number;

    ShipCountry?: string;

    ShipAddress?: string;

}

how can I do this?


16 Replies

SI Santhosh Iruthayaraj Syncfusion Team May 1, 2024 01:01 PM UTC

Hi Buddhi,


Greetings from Syncfusion Support!


You can resolve the current scenario you are facing by simply setting the "orderData" property to an empty object when declaring it. Please refer to the code snippet and sample below for your reference:


[app.component.ts]

 

export class AppComponent {

  public dataObject[];

  public editSettingsObject;

  public toolbarstring[];

  .  .  .  .  .

  public orderDataIOrderModel = {};

 


Sample: Angular Grid Template Editing - StackBlitz


Please let us know if you have any further queries.


Regards,
Santhosh I



B- Buddhi - BLUE LOTUS 360 replied to Santhosh Iruthayaraj May 3, 2024 06:52 AM UTC

yeah, then it is working fine. but what has happened when does this change? can you explain it to me 



AR Aishwarya Rameshbabu Syncfusion Team May 6, 2024 01:00 PM UTC

Hi Buddhi,


This is due to the fact that when ‘orderData’ is not initialized, it becomes undefined, which can lead to script issues when trying to access its property in an ngForm. However, if orderData is initialized with an empty object, accessing its property won't throw an error. This is because orderData is an object, and accessing a property of an object that doesn't exist returns undefined without causing an error.


Regards

Aishwarya R



B- Buddhi - BLUE LOTUS 360 May 7, 2024 10:20 AM UTC

Hello, Thanks for your help. I understood the above answer,

However, I use the Syncfusion Angular Grid in my custom Angular component. My grid is intended to have the first row always editable when showAddNewRow: true is enabled. However, this functionality isn't working as expected in my code.

Here's the relevant snippet of my Angular component template and class, showing how I've configured the Syncfusion Grid:

<style>
.control-section{
    margin-top: 100px;
}


</style>
<div class="control-section">


    <ejs-grid #blgrid
          id='blgrid'
          [dataSource]="lineItems"
          [editSettings]='editSettings'
          [pageSettings]='pageSettings'
          [toolbar]='toolbar'
          rowHeight='40'
          height="300px">
    <e-columns>


        @for (col of columns; track col){
        <e-column [field]='col.field' [headerText]='col.headerText' *ngIf="!col.isHidden"
                  [textAlign]='col.textAlign' [isPrimaryKey]='col.isPrimaryKey'
                  [allowEditing]='col.allowEditing' [editType]='col.editType' [edit]='col.edit'>


        </e-column>
        }

    </e-columns>
    <ng-template #editSettingsTemplate let-data>
        <div ngForm #orderForm="ngForm">
            <table class="e-table e-inline-edit" cellspacing="0.25">
                <colgroup>
                    @for (col of columns; track col)
                    {
                        @if(!col.isHidden)
                        {
                            <col style="width:120px;">
                        }
                    }
                </colgroup>
                <tbody>
                    <tr>
                        <td *ngFor="let col of gridDefinition.children" class='e-rowcell'>
                            @if(col.isVisible)
                            {
                                <app-numeric-box *ngIf="col.elementType==='NumericBox'" [data]="selectedLineItem"></app-numeric-box>
                                <app-text-box *ngIf="col.elementType==='TextBox'" [data]="selectedLineItem" ></app-text-box>
                                <app-dropdown *ngIf="col.elementType==='DropDown'" [data]="selectedLineItem"></app-dropdown>
                            }


                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </ng-template>
    <ng-template #emptyRecordTemplate>
        <div class='emptyRecordTemplate'>
            <img src="./assets/img/grid/emptyRecordTemplate.svg" class="e-emptyRecord" alt="No record">
            <span>No data available to display at the moment.</span>
        </div>
    </ng-template>
</ejs-grid>




</div>


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    providers: [
      PageService,
      ToolbarService,
      EditService
    ],
    encapsulation: ViewEncapsulation.None,
  })
  export class LineItemGridComponent implements OnInit {


    @Input() uiDef!: UIObject;
    @Input() lineItems!:OrderItem[]
    constructor() {
    }


    @ViewChild('blgrid')
    public blgrid?: GridComponent;
    @ViewChild('orderForm')
    public orderForm!: FormGroup;


    title = 'bl-grid';
    public rowMode: string = 'Vertical';
    public pageSettings: Object = { pageCount: 4, pageSizes: true };
    public toolbar!: Object[];
    public toolbarOptions?: ToolbarItems[];
    public editSettings?: EditSettingsModel;
    gridDefinition!: UIObject;
    public columns: any[] = []
    selectedLineItem:OrderItem=new OrderItem()


    ngOnInit(): void {
      this.editSettings = { allowEditing: true,
                            allowAdding: true,
                            allowDeleting: true,
                            showConfirmDialog: false,
                            showDeleteConfirmDialog: true,
                            showAddNewRow :true,
                            newRowPosition: 'Top',
                            mode:'Normal' };
      this.pageSettings = { pageCount: 5, pageSizes: true };
      this.gridDefinition = this.uiDef.children.filter(x => x.elementType === 'Grid')[0];


      this.columnPreProcessor();




    }


    columnPreProcessor() {


      this.gridDefinition.children.forEach((col) => {
        let row: any = {};
        row.isPrimaryKey = false;
        row.field = col.mapName;
        row.headerText = col.elementCaption;
        row.width = col.width;
        row.isHidden = !col.isVisible;
        row.allowEditing = col.isEnable;
        if (col.elementType === 'DropDown') {
          row.textAlign = 'Center';
          row.editType = 'dropdownedit';
        }
        else if (col.elementType === 'NumericBox') {
          row.textAlign = 'Right';
          row.editType = 'numericedit';
        }
        else if (col.elementType === 'TextBox') {
          row.textAlign = 'Left';
          row.editType = 'stringedit';


        }






        this.columns.push(row);


      });


    }




  }

The component has @Input() properties (uiDef, lineItems), used to set the grid's structure and data source.

Despite setting showAddNewRow: true, the first row doesn't become editable as expected. I've checked the Syncfusion documentation and tried some suggested fixes, but the problem persists.

Could you please guide me on what might be causing this issue? Are there any additional configurations or checks I should consider?

Thank you in advance for your assistance!



AR Aishwarya Rameshbabu Syncfusion Team May 8, 2024 12:39 PM UTC

Hi Buddhi,


Upon reviewing your query, it appears that you are encountering difficulties with editing the new row positioned at the top, even after setting showAddNewRow property of Grid to true. In order to assist you further, kindly provide the following details for us to validate the issue:


  1. Based on the shared code example, we could see that you are using dynamic column rendering in the Grid and the creation of column object is based on the data returned from the parent component. So please share the details of the data being returned, whether it is local or remote data. If remote data is being used, please share the adaptor details and the code lines defining the DataManager.
  2. If possible, please share the data object or a screenshot of the data object returned.
  3. Based on the format of the data being used, we could be able to update the sample to recreate the issue and validate it further.
  4. Otherwise, if possible, please share a simple issue replication sample along with a video demonstration of the issue you are facing.
  5. Also, Share the Syncfusion package version you are using currently.


Providing the requested information will enable us to offer a solution promptly. We look forward to hearing from you.


Regards

Aishwarya R



B- Buddhi - BLUE LOTUS 360 May 9, 2024 09:35 AM UTC

ok fine.

this is my grid component


<style>
.control-section{
margin-top:100px;
}


</style>
<divclass="control-section">


<ejs-grid #blgrid
id='blgrid'
[dataSource]="lineItems"
[editSettings]='editSettings'
[pageSettings]='pageSettings'
[toolbar]='toolbar'
rowHeight='40'
height="300px">
<e-columns>








@for (col of columns; track col){
<e-column [field]='col.field' [headerText]='col.headerText' *ngIf="!col.isHidden"
[textAlign]='col.textAlign' [isPrimaryKey]='col.isPrimaryKey'
[allowEditing]='col.allowEditing' [editType]='col.editType' [edit]='col.edit'>








</e-column>
}




</e-columns>
<ng-template #editSettingsTemplatelet-data>
<divngForm #orderForm="ngForm">
<tableclass="e-table e-inline-edit"cellspacing="0.25">
<colgroup>
@for (col of columns; track col)
{
@if(!col.isHidden)
{
<colstyle="width:120px;">
}
}
</colgroup>
<tbody>
<tr>
<td *ngFor="let col of gridDefinition.children"class='e-rowcell'>
@if(col.isVisible)
{
<app-numeric-box *ngIf="col.elementType==='NumericBox'" [data]="selectedLineItem"></app-numeric-box>
<app-text-box *ngIf="col.elementType==='TextBox'" [data]="selectedLineItem"></app-text-box>
<app-dropdown *ngIf="col.elementType==='DropDown'" [data]="selectedLineItem"></app-dropdown>
}








</td>
</tr>
</tbody>
</table>
</div>
</ng-template>
<ng-template #emptyRecordTemplate>
<divclass='emptyRecordTemplate'>
<imgsrc="./assets/img/grid/emptyRecordTemplate.svg"class="e-emptyRecord"alt="No record">
<span>No data available to display at the moment.</span>
</div>
</ng-template>
</ejs-grid>
















</div>








@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [
PageService,
ToolbarService,
EditService
],
encapsulation: ViewEncapsulation.None,
})
export class LineItemGridComponent implements OnInit {








@Input() uiDef!: UIObject;
@Input() lineItems!:OrderItem[]
constructor() {
}








@ViewChild('blgrid')
public blgrid?: GridComponent;
@ViewChild('orderForm')
public orderForm!: FormGroup;








title = 'bl-grid';
public rowMode: string = 'Vertical';
public pageSettings: Object = { pageCount: 4, pageSizes: true };
public toolbar!: Object[];
public toolbarOptions?: ToolbarItems[];
public editSettings?: EditSettingsModel;
gridDefinition!: UIObject;
public columns: any[] = []
selectedLineItem:OrderItem=new OrderItem()








ngOnInit(): void {
this.editSettings = { allowEditing: true,
allowAdding: true,
allowDeleting: true,
showConfirmDialog: false,
showDeleteConfirmDialog: true,
showAddNewRow :true,
newRowPosition: 'Top',
mode:'Normal' };
this.pageSettings = { pageCount: 5, pageSizes: true };
this.gridDefinition = this.uiDef.children.filter(x => x.elementType === 'Grid')[0];








this.columnPreProcessor();
















}








columnPreProcessor() {


this.gridDefinition.children.forEach((col) => {
let row: any = {};
row.isPrimaryKey = false;
row.field = col.mapName;
row.headerText = col.elementCaption;
row.width = col.width;
row.isHidden = !col.isVisible;
row.allowEditing = col.isEnable;
if (col.elementType === 'DropDown') {
row.textAlign = 'Center';
row.editType = 'dropdownedit';
}
else if (col.elementType === 'NumericBox') {
row.textAlign = 'Right';
row.editType = 'numericedit';
}
else if (col.elementType === 'TextBox') {
row.textAlign = 'Left';
row.editType = 'stringedit';


}


this.columns.push(row);


});


}




}


the thing is I can not hardcode the grid. I have to render it dynamically. grid-column details coming with the uiDef object have included a property called children.it is also the UIObject type list, let me show you that class.


export class UIObject {
    _internalElementName!: string
    elementCaption!: string
    elementID!: string
    elementType!: string
    defaultAccessPath!: string
    defaultValue!: string
    mapName!: string
    elementKey!: number
    parentKey!: number
    width!: number
    objectTypeKey!: number
    isVisible!:boolean
    isEnable!:boolean
    children!: UIObject[]
    //other properties
}


so I can get all the column details from the parent component and push those details to the columns list.

then need to get the data source also to the grid component. its type is OrderItem.


export class OrderItem{
    orderKey: number=1;
    orderDate!: Date;
    orderNumber!: string;
    documentNumber!: string;
    yourRef!string;
    approveState!: CodeBaseResponse;


}

I am passing the list of OrderItem to the grid component from the parent component. this is a sample JSON array for that list


[


    {
        "orderKey": 1390746,
        "orderDate": "2024-04-16T00:00:00",
        "orderNumber": "2901",
        "documentNumber": "",
        "yourReference": "",
        "approveState": {
            "codeKey": 1,
            "code": "",
        }
    },
    {
        "orderKey": 1391272,
        "orderDate": "2024-04-18T00:00:00",
        "orderNumber": "2903",
        "documentNumber": "",
        "yourReference": "",
        "approveState": {
            "codeKey": 1,
            "code": "",
        }
    },
]

Note


  1. I am using syncfusion "@syncfusion/ej2-angular-grids": "^25.1.35" version
  2. These uiDef and lineItems are both from the parent component and are remote data.

I have attached a screenshot of my grid. if data is not filled to the grid, it shows no data template. but I need to show the editable new row. Even though I added that showAddNewRow as true it is not working with this. if you want any other details ,please let me know.


sf-and-grid.png



AR Aishwarya Rameshbabu Syncfusion Team May 21, 2024 08:45 AM UTC

Hi Buddhi,


We have logged an issue with enabling ‘ShowAddNewRow’ in editSettings of template driven forms as “When we enable 'ShowAddNewRow' in editSettings of template driven forms, after adding a record and updating does not reset the form elements. At Syncfusion, we are committed to fixing all validated defects (subject to technical feasibility and Product Development Life Cycle ) and will include the defect fix in our upcoming patch release which will be rolled out on “June 5th,  2024”.


You can now track the current status of your request, review the proposed resolution timeline, and contact us for any further inquiries through the below link,


Feedback: https://www.syncfusion.com/feedback/57944/showaddnewrow-in-editsettings-of-template-driven-forms-after-adding-and-updating


Disclaimer: "Inclusion of this solution in the weekly release may change due to other factors including but not limited to QA checks and works reprioritization".


Regards

Aishwarya R



JS Johnson Soundararajan S Syncfusion Team June 5, 2024 05:44 PM UTC

Hi Buddhi - BLUE LOTUS 360,

 

We sincerely apologise for the inconvenience caused.

 

We understand that you are eagerly awaiting the patch to address the matter, and we wanted to provide you with an update regarding the delay. Currently, we are encountering some complexity in addressing those cases. We will fix the reported issue with "When we enable 'ShowAddNewRow' in editSettings of template driven forms, after adding a record and updating does not reset the form elements" and include it in the first weekly patch release after the Vol 2 Main release, which is scheduled for June 19th, 2024.


 

Again, we sincerely apologise for the delay and any inconvenience caused. We greatly appreciate your understanding and patience.
 

Regards,

Johnson Soundararajan S



AR Aishwarya Rameshbabu Syncfusion Team June 21, 2024 01:52 PM UTC

Hi Buddhi,


Sorry for the inconvenience caused.


Upon conducting a comprehensive analysis, it has been determined that 'showAddNewRow' is not currently supported with editTemplates due to its reliance on two-way binding concepts. We have considered the report case as an improvement feature on our end and logged a task titled “Need to provide support for ‘showAddNewRow’ with editTemplates. During the planning stage for each release cycle, we review all open features and identify those for implementation based on specific parameters such as product vision, technological feasibility, and customer interest. This feature will be included in one of our upcoming releases.


You can now track the current status of your request, review the proposed resolution timeline, and contact us for any further inquiries through this link.


Feedback:
https://www.syncfusion.com/feedback/57944/showaddnewrow-in-editsettings-of-template-driven-forms-after-adding-and-updating


We do not have an immediate plan to implement this feature, but it will be included in one of our upcoming releases. Please cast your vote on this feature. Based on the customer demand we will prioritize the features in our upcoming road map. You can communicate with us regarding open features at any time using the above feedback link.


Regards

Aishwarya R



B- Buddhi - BLUE LOTUS 360 replied to Aishwarya Rameshbabu July 21, 2024 09:15 AM UTC

Thank you for your detailed response and for investigating the issue with the 'showAddNewRow' functionality in conjunction with editTemplates.

I understand that 'showAddNewRow' is currently unsupported due to its dependency on two-way binding concepts. I appreciate that you have logged this as a potential improvement feature titled “Need to provide support for ‘showAddNewRow’ with editTemplates”.


To provide further clarity, I have created a working example on StackBlitz that demonstrates the issue. Despite setting showAddNewRow: true, the first row does not become editable as expected. I have reviewed the Syncfusion documentation and tried some suggested fixes, but the problem persists. You can view the working example here:

https://stackblitz.com/edit/stackblitz-starters-rsxh1w?file=src%2Fcomponent%2Fdata-grid%2Fdata-grid.component.ts

I need to know if this approach is correct for my requirements. If not, please explain how I can achieve this using an alternative way. We are moving forward with Syncfusion Angular products for our future developments, so your assistance in resolving this issue is highly appreciated.


I will keep track of the status of this request and the proposed resolution timeline via the provided feedback link. I have also cast my vote for this feature to emphasize its importance.


https://www.syncfusion.com/feedback/57944/showaddnewrow-in-editsettings-of-template-driven-forms-after-adding-and-updating


Thank you for considering this improvement. I look forward to its implementation in a future release. If I have any further inquiries, I will use the feedback link to communicate with you.


Best regards,

Buddhi



AR Aishwarya Rameshbabu Syncfusion Team July 24, 2024 11:20 AM UTC

Hi Buddhi,


Upon reviewing the provided sample, it has come to our attention that template-driven forms are being used to update Grid data with inline mode of editSettings. You are attempting to incorporate the "showAddNewRow" feature with your Grid. Currently, our component does not provide support for utilizing "showAddNewRow" in conjunction with editTemplates and we have considered this as an improvement feature on our end.


In Syncfusion Angular Grid, the template driven forms for editing operations rely on the concept of two-way binding. The elements and components used in the template forms utilize ngModel to bind each form control to the corresponding grid data field. This ensures that each control is part of an ngForm, allowing for validation and submission as part of the form. The updated data is then transferred to the Grid within the actionComplete event.


Therefore, we recommend implementing the template-driven approach of editing using ngModel and the two-way binding concept in your application. For more detailed information and guidance on utilizing template driven forms for editing with the Grid, please refer to the provided sample and code example.


App.component.html

 

        <ng-template #editSettingsTemplate let-data>

            <div ngForm #orderForm="ngForm">

                <table class="e-table e-inline-edit" cellspacing="0.25">

                    <colgroup>

                             ……………………,

                    </colgroup>

                    <tbody>

                        <tr>

                            <td style="text-align: right" class='e-rowcell'>

                                <div class="e-input-group" [ngClass]= "{'e-disabled': !data.isAdd}">

                                    <input class="e-input e-field" [(ngModel)]="orderData.OrderID" required [attr.disabled]="!data.isAdd ? '' : null" name='OrderID' type="text" (focus)="focusIn($event.target)"

                                        (blur)="focusOut($event.target)" #OrderID style="text-align: right"  />

                                </div>

                            </td>

                            <td class='e-rowcell'>

                                <div class="e-input-group">

                                    <input class="e-input e-field" name='CustomerName' [(ngModel)]="orderData.CustomerName" required type="text" (focus)="focusIn($event.target)"

                                        (blur)="focusOut($event.target)" #CustomerName />

                                </div>

                            </td>

                            <td style="text-align: right" class='e-rowcell'>

                                <ejs-numerictextbox name="Freight" id="Freight" [(ngModel)]="orderData.Freight" floatLabelType='Never'></ejs-numerictextbox>

                            </td>

                            <td style="text-align: right" class='e-rowcell'>

                                <ejs-datepicker id="OrderDate" name="OrderDate" [(ngModel)]="orderData.OrderDate" floatLabelType='Never'></ejs-datepicker>

                            </td>

                            <td class='e-rowcell'>

                                <ejs-dropdownlist id="ShipCountry" name="ShipCountry" [(ngModel)]="orderData.ShipCountry" [dataSource]='shipCountryDistinctData' [fields]="{text: 'ShipCountry', value: 'ShipCountry' }" popupHeight='300px' floatLabelType='Never'></ejs-dropdownlist>

                            </td>

                        </tr>

                    </tbody>

                </table>

            </div>

        </ng-template>

 

App.component.ts

 

    actionBegin(args: SaveEventArgs): void {

        if (args.requestType === 'beginEdit' || args.requestType === 'add') {

            this.orderData = Object.assign({}, args.rowData); // Assigning the current editable data to orderData(data bind to the template form)

        }

        if (args.requestType === 'save') {

            if (this.orderForm.valid) {

                args.data = this.orderData; // Assigning the updated value of orderData to args.data to be updated in Grid

            } else {

                args.cancel = true;

            }

        }

    } 

    actionComplete(args: DialogEditEventArgs): void {

        if (args.requestType === 'beginEdit' || args.requestType === 'add') {

            // Set initail Focus upon editing or adding a new record

            if (args.requestType === 'beginEdit') {

                (args.form.elements.namedItem('CustomerName') as HTMLInputElement).focus();

            } else if (args.requestType === 'add') {

                (args.form.elements.namedItem('OrderID') as HTMLInputElement).focus();

            }

        }

    }

 


Sample: Mv4xwa (forked) - StackBlitz


If you still encounter any issues, please get back to us.



Regards

Aishwarya R



B- Buddhi - BLUE LOTUS 360 July 29, 2024 06:25 AM UTC

Though I define it without the ngModel validations, data bindings work fine. because  I am doing the validations in the form level and data binding also works internally and dynamically. anyway, I updated the above sample using  ngModel . can you check it??

https://stackblitz.com/edit/stackblitz-starters-rsxh1w?file=src%2Fcomponent%2Funit-combo-box%2Funit-combo-box.component.html



B- Buddhi - BLUE LOTUS 360 July 30, 2024 07:45 PM UTC

Hi, I have another query, is there a way to alter the behavior of the delete top button action? it means when I press the delete button on the grid toolbar I can not delete the item completely from the list in the table. instead of doing that I need to inactive it and keep it there. but can't show it on the table. How can I do that?

you can find a working sample here

https://stackblitz.com/edit/stackblitz-starters-rsxh1w?file=src%2Fcomponent%2Funit-combo-box%2Funit-combo-box.component.html



AR Aishwarya Rameshbabu Syncfusion Team August 2, 2024 12:24 PM UTC

Hi Buddhi,


We have reviewed the updated sample. In your application you are using dynamic column binding, but it lacks a primary key column. For editing actions, the Grid requires at least one column with a primary key enabled. In your application you have set the property isPrimaryKey to false for all the columns. You need to enable this for any one for the columns used in the Grid.


The use of ngModel in form elements facilitates two-way data binding, ensuring synchronization between form inputs and the component's data model. When a value is updated in the component, the data model reflects this change due to the ngModel binding. This data can then be accessed and saved to the Grid data during the Grid's actionBegin event.


In your application, components are dynamically rendered within the edit template as individual Angular components. The use of ngModel is restricted to the component level and is not integrated with the form data, leading to incorrect data rendering and updating within the Grid.


For additional details, please follow the steps below along with the provided example:


Sample: Ddhugg (forked) - StackBlitz


  1. When a record is initially added, orderData (data bound to form elements) is undefined.



  1. It is then initialized with edited data using args.rowData.



  1. Form elements will display the edited data as they are bound with the ngModel value of orderData



  1. Upon editing records, the edited values update the corresponding orderData objects.



  1. These updates will reflect in the Grid data.


This suggests a flow for utilizing template-driven forms with the Syncfusion Grid component. Therefore, it is advised to update your application accordingly based on this guidance.


In response to your second query concerning the deletion of the record, we require some additional information. Kindly provide the following details:

1. Kindly provide detailed information regarding your specific requirements for record deletion within the Grid.

2. Please confirm if you intend to set the isActive property to 0 in the 'selectedLineItem' upon clicking the delete button, rather than removing the actual record. If yes, please describe the use case of this scenario.

3. Furthermore, clarify whether you prefer to display the deleted record in an inactive state within the Grid or to completely remove it from the Grid.



Regards

Aishwarya R



B- Buddhi - BLUE LOTUS 360 August 9, 2024 04:28 PM UTC

Hi, I have found the solution for this. what I did was I used the addRecord() function in the dataBound event of the grid. a working example is here. thanks for the support.

https://stackblitz.com/edit/stackblitz-starters-rsxh1w?file=src%2Fcomponent%2Fdata-grid%2Fdata-grid.component.ts



AR Aishwarya Rameshbabu Syncfusion Team August 12, 2024 01:20 PM UTC

Hi Buddhi,


We are happy to hear that you have successfully resolved the reported issue. Please get back to us if you need any other assistance.


Regards

Aishwarya R


Loader.
Up arrow icon