add New Row with Contextual Search

I am using this Example https://stackblitz.com/edit/angular-efjsmp-ulvs8d?file=app.component.html  for adding a new row in the Grid. I am looking at adding a functionality where user clicks on add button. which will bring up blank row ( Demo does exactly that)  then for example if user types few characters in customer ID column, then it will show suggested values from master array. Something like how Google search suggest terms. 


10 Replies

BS Balaji Sekar Syncfusion Team November 10, 2021 12:27 PM UTC

Hi Parth Rawal, 

Greetings from the Syncfusion support. 

Based on your query you want to search option in input component(CustomerID) when user types few characters since we suggest you to use EJ2 AutoComplete component and it will search value from AutoComplete’s dataSource. Now you can bind new record with user types values to Grid. 

Please refer the below code example and sample for more information. 

[app.component.html] 
 <ejs-autocomplete 
      id="CustomerID" 
      width="200" 
      [dataSource]="data" 
      [fields]="fields" 
    ></ejs-autocomplete> 
 

[app.component.ts] 
addRecord() { 
    this.record = { 
      OrderID: Number(document.getElementById('OrderID').value), 
      EmployeeID: Number(document.getElementById('EmployeeID').value), 
      CustomerID: document.getElementById('CustomerID').ej2_instances[0].value, 
      Title: document.getElementById('checkvalue').checked, 
    }; 
    this.grid.addRecord(this.record); 
  } 
 


Please get back to us, if you need further assistance. 

Regards, 
Balaji Sekar. 



PD PDev November 10, 2021 01:02 PM UTC

I am looking at the autocomplete functionality within grid cell it self. when you click on Add new Row and it will add blank row. and autocomplete functionality is available for desired cell within row. 

your example is looking at the autocomplete outside grid.



JC Joseph Christ Nithin Issack Syncfusion Team November 11, 2021 12:34 PM UTC

Hi Parth Rawal,  Thanks for your update.   Based on your requirement, you want an autocomplete inside the grid cell when you add a new row. your requirement can be achieved by using the `editSettingsTemplate` of the EJ2 Grid. please refer the below code example: 
<div class="control-section"> 
  <ejs-grid 
    [dataSource]="data" 
    allowPaging="true" 
    [pageSettings]="pageSettings" 
    [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" 
                  required 
                  [(ngModel)]="orderData.OrderDate" 
                  floatLabelType="Never" 
                ></ejs-datepicker> 
              </td> 
              <td class="e-rowcell"> 
                <ejs-autocomplete 
                  id="ShipCountry" 
                  name="ShipCountry" 
                  [(ngModel)]="orderData.ShipCountry" 
                  [dataSource]="shipCountryDistinctData" 
                  [fields]="{ text: 'ShipCountry', value: 'ShipCountry' }" 
                  popupHeight="300px" 
                  floatLabelType="Never" 
                ></ejs-autocomplete> 
              </td> 
            </tr> 
          </tbody> 
        </table> 
      </div> 
    </ng-template> 
  </ejs-grid> 
</div> 
Documentationhttps://ej2.syncfusion.com/angular/documentation/grid/edit/#template-driven-formsPlease find the attached sample and revert for more queries.Regards,Joseph I. 



PD PDev November 17, 2021 09:50 AM UTC

Thanks for the response. Few Questions


  1. Can it be possible to hook it up with API instead of static data ? 
  2. Will it be possible to give me example using typescript, instead of doing it from HTML, as my code has dynamic columns,  
  3.  In your example you have modified other columns using edit templates, Hopefullyi can apply it just for one column instead of all. I am siure answer to this is YES. But still :) 


MF Mohammed Farook J Syncfusion Team November 18, 2021 10:17 AM UTC

Hi PDev, 
 
Yes, you can use your API to get data for the Autocomplete component. But, before starting your requirement, we need the following confirmation, 
 
  1. Do you have bound remote data or local data in your Grid?
  2. Share with us complete Grid code example?
  3. Do you want to initialize the Grid column through typescript ?
  4. If you are using remote data means, can you please share with us which type service used in your Grid?
  5. Do you want to render autocomplete components for all columns while editing? , if the is not meet your requirement could you please more details about your requirement
 
 
 
Please let us know if you have any concerns. 
 
Regards,  
J Mohammed Farook 
 



PD PDev November 18, 2021 12:08 PM UTC

  1. Do you have bound remote data or local data in your Grid? - remote sharepoint REST API
  2. Share with us complete Grid code example?
  3. Do you want to initialize the Grid column through typescript ? YES
  4. If you are using remote data means, can you please share with us which type service used in your Grid? 
  5. https://teams.SharePoint.com/_api/web/siteusers?$filter=substringof('" + term + "'," + columnName + ") eq true
  6. Do you want to render autocomplete components for all columns while editing? , No


PD PDev November 18, 2021 12:12 PM UTC

Code which is not working against ResouceName column. out of the box it applies TOLOWER which is not allowed in Sharepoint REST API. because of which my code is failing to fetch the infromation.

If i can construct my own URL for search or there is another way to search. If I construct my own URL then I will be needing the idea as to how can i pass my search term as user types in data. Also, I am required to populate other columns in grid once user searches name in auto complete and then populate data in other columns like ResourceType, Internal/External etc.

cols.push(
{ field: 'ResourceType', headerText: 'Resource Type', textAlign: 'Left',type:'string', width: 150,isFrozen:false,allowResizing:true},
{ field: 'ResourceName', headerText: 'Resource Name', textAlign: 'Left', type:'string',
// edit: {
// create: function () {
// elem = document.createElement('input');
// return elem;
// },
// read: function () {
// return dObj.value;
// },
// destroy: function () {
// //dObj.destroy();
// },
// keydown:function(args){
// console.log(args);
// },
// write: function (args) {
// let columnName="Title";
// let term="Byr";
// let predicate: Predicate = new Predicate('EmployeeID', 'equal', 3);
// predicate = predicate.or('EmployeeID', 'equal', 2);
// //$filter=substringof('" + term + "'," + columnName + ") eq true
// // .executeQuery(new Query().search('Byr', ['Title']))
// // .then((e: ReturnOption) => this.items = e.result as object[]).catch((e) => true),
// dObj =new AutoComplete({
// dataSource: new DataManager({
// url: "https://teams.mdlz.com/_api/web/siteusers?$select=Title",
// adaptor: new ODataAdaptor(),
// crossDomain: true,
// headers: [{"accept": "application/json;odata=verbose" }]
// }),
// fields:{"text":"Title","value":"Title"},
// value: args.rowData["Title"] ? args.rowData["Title"] : "",
// });
// dObj.appendTo(elem);
// }
// },
width: 150,isFrozen:false,allowResizing:true},
{ field: 'ResourceDesignation', headerText: 'Resource Designation', textAlign: 'Left',type:'string', width: 150,isFrozen:false,allowResizing:true},
);


RS Rajapandiyan Settu Syncfusion Team November 19, 2021 11:46 AM UTC

Hi PDev,  
   
Thanks for your update. 
  
Based on your query, you want to perform all the Grid actions on your own service manually. In EJ2 Grid, we have the support for custom data-binding. By using this feature, you can handle the data for all the grid actions using your own service. Refer to the below documentation for more information.  
 
  
 
We would like to share the behavior of custom-binding in EJ2 Grid.   
  
For every grid actions(such as FilterPage, etc.,), we have triggered the dataStateChange event and, in that event arguments we have send the corresponding action details(like skip, take, filter field, value, sort direction, etc.,) based on that, you can perform the action in your service and return the data as a result and count object.    
  
Note: ‘dataStateChange’ event is not triggered at the Grid initial render. If you are using a remote service, you need to call your remote service by manually with a pagination query (need to set skip value as 0 and take value based on your pageSize of pageSettings in Grid. If you are not defined pageSize in pageSettings, you need to send the default value 12 ) in ngOnInit. Please return the result like as “{result: […], count: …}” format to Grid.   
  
dataSourceChanged’ event is triggered when performing CRUD action in Grid. You can perform the CRUD action in your service using action details from this event and, you need to call the endEdit method to indicate the completion of save operation.   
 
 
We have prepared a simple sample based on your requirement.   
   
 
When you perform the search action, the dataStateChange event will be triggered. In that event, you can get the search query details. Using this you can generate your own URL and return the result and count format data to the Grid. 
  
Screenshot: 
 
 
Please get back to us if you need further assistance  
   
Regards,   
Rajapandiyan S   



PD PDev November 19, 2021 12:18 PM UTC

My requirement is very simple. I want to have search functionality in my grid cell. I dont understand  whether i am not able to explain or i am not able to understand what you guys are explaining it to me. 


I have 2 Tables and 2 APIs. one is master and second is child. When I expand Parent/Master row. I want to bind the Child grid. Which i am able to do it. Now, within this child grid I have add Row functionality. which is working just fine. Once user adds a new row. one of the column needs to have search functinality which will auto complete user's search and suggests some user names. JQUERY can do this really easily.... 


Please refer to below code in Javascript. Which is working just fine where i am not using syncfusion controls


initAutocomplete() {
var ctrl = $("#Name");
ctrl.keydown(function (event) {
if(event.type=="keydown"){
$("#loading").show();
ctrl.autocomplete({
source: this.getSource1,
delay: 200,
change: function (event, ui) {
$("#loading").hide();
var source = $(this).val();
var temp = $(".ui-autocomplete li").map(function () { return $(this).text() }).get(); //get the selected projectname
var found = $.inArray(source, temp);
console.log(found);
if (found < 0) {
$(this).val(''); //this clears out the field if non-existing value in <select><options> is typed.
}else{
//use source variable to get the value
}
}
});
}
});
}
getSource1(request:any, response) {
var term = request.term;
var items = [];
var columnName = 'Title';
var requestUri = "https://sharepoint.com/_api/web/siteusers?$filter=substringof('" + term + "'," + columnName + ") eq true";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
async: false,
error: function (error) { alert("Error: Could not read values."); },
success: function (data, request) {
let results = data.d.results;
for (var i = 0; i < results.length; i++) {
items.push(results[i][columnName]);
}
}
});
response(items);
}


BS Balaji Sekar Syncfusion Team November 23, 2021 08:54 AM UTC

Hi Parth, 
  
We have created a new incident under your Direct trac account to follow up with this query. We suggest you follow up with the incident for further updates. 
  
Please log in using the below link.   
  
  
Regards,  
Balaji Sekar. 


Loader.
Up arrow icon