How to sort the dates in Kendo Grid Angular?
Kendo gird taking the date values as string and sorts it
When you configure the grid's dataSource property, you should be defining the schema. If you set the schema's model's field's type to date then you should get the expected results.
For example:
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "https://my-api/my-endpoint"
},
schema: {
model: {
fields: {
Date: { type: "date" }
}
}
}
},
sortable: true,
columns: [
{ field: "Date", title: "Date", format: "{0:dd-MM-yyyy}" }
]
});
Demo: https://dojo.telerik.com/ugItIKob
Update
You indicated that you needed an Angular example. In this situation, define the property representing the date field as a Date and format it in template using the date pipe.
For example:
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `
<kendo-grid [kendoGridBinding]="gridData" [sortable]="true">
<kendo-grid-column field="ProductId" title="ID"></kendo-grid-column>
<kendo-grid-column field="ProductName" title="Name"></kendo-grid-column>
<kendo-grid-column field="Cost" title="Price">
<ng-template kendoGridCellTemplate let-dataItem>
{{ dataItem.Cost | currency:'USD':'symbol' }}
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="PurchaseDate" title="Date">
<ng-template kendoGridCellTemplate let-dataItem>
{{ dataItem.PurchaseDate | date:'dd-MM-yyyy' }}
</ng-template>
</kendo-grid-column>
</kendo-grid>
`,
})
export class AppComponent {
public gridData: IProduct[] = [
{
ProductId: 1,
ProductName: 'Chai',
Cost: 18,
PurchaseDate: new Date('2022-08-03'),
},
{
ProductId: 2,
ProductName: 'Chang',
Cost: 19,
PurchaseDate: new Date('2023-08-03'),
},
{
ProductId: 3,
ProductName: 'Aniseed Syrup',
Cost: 10,
PurchaseDate: new Date('2021-08-17'),
},
];
}
export interface IProduct {
ProductId?: number;
ProductName?: string;
Cost?: number;
PurchaseDate?: Date;
}
Demo: https://stackblitz.com/edit/angular-metwta?file=src%2Fapp%2Fapp.component.ts
Related
this is my first question in stakeoverflow. i'm new user in vuejs and vue-table-2. from the column i have no problem but i want to fill the rows with my data from my table in database. two days i just search in google to solve this problem. any one one can solve this problem?
<template>
<div class="row">
<div class="col-lg-12 mb-3">
<b-card header="Data Paket" header-tag="h4" class="bg-success-card">
<datatable title :rows="rowdata" :columns="columndata"></datatable>
</b-card>
</div>
</div>
</template>
<script>
import Vue from "vue";
import axios from "axios";
import { ClientTable, Event } from "vue-tables-2";
import datatable from "components/plugins/DataTable/DataTable.vue";
Vue.use(ClientTable, {}, false);
export default {
components: {
datatable
},
data() {
return {
rowdata: [],
columndata: [
// Array of objects
{
label: "Name", // Column name
field: "fname", // Field name from row
numeric: false, // Affects sorting
width: "200px", //width of the column
html: false // Escapes output if false.
},
{
label: "Last Name",
field: "lname",
numeric: false,
html: false
},
{
label: "age",
field: "age",
numeric: true,
html: false
},
{
label: "state",
field: "state",
numeric: false,
html: false
},
{
label: "Action",
field: "button",
numeric: false,
html: true
}
]
};
},
};
</script>
I am trying to build a Vue input component using vee-validate for input error messages. All the errors are working correctly, but when I try to confirm two inputs with each other, the error message pops up but never goes away.
My component:
<template lang="pug">
div
.label {{ label }}
input(:type="type"
:value="value"
#input="$emit('input', $event.target.value)"
#change="$emit('input', $event.target.value)"
:placeholder="placeholder"
v-validate="validation"
:name="name"
:ref="name")
.message
img(v-if="errors.first(name)" src="/static/icons/error-input.svg")
.field(v-if="errors.first(name)") {{ errors.first(name) }}
</template>
<script>
export default {
inject: ['$validator'],
$_veeValidate: {
name () {
return this.name
},
value () {
return this.value
}
},
props: {
label: {
type: String,
required: false
},
placeholder: {
type: String,
required: false
},
validation: {
type: String,
required: false,
default: ''
},
type: {
type: String,
default: 'text',
required: false
},
value: {
type: String
},
name: {
type: String
}
}
}
</script>
How I call it from the parent component when I want to confirm two e-mails:
<template lang="pug">
v-form
text-input(v-model="email"
validation="required|email"
name="email")
text-input(v-model="confirm_email"
validation="required|email|confirmed:email"
name="confirm_email")
</template>
<script>
import { mapActions } from 'vuex'
import textInput from '#/newDesignComponents/inputs/input'
export default {
$_veeValidate: {
validator: 'new' // please set a $validator for this component
},
data () {
return {
email: null,
confirm_email: null
}
},
components: {
textInput
}
}
</script>
Would be great if anybody could help me out!
New to both angular and kendo-ui
Below is the code, all the data except the startTime and endTime doesn't show up on the Kendo-ui Grid.Using Angular 5, Kendo-ui and ASP.Net Core 2, EF Core.
Below is the HTML,ts and sample data
dailyMachineNotes.component.html
<div>
<kendo-grid [kendoGridBinding]="breakDownData"
[filterable]="true"
scrollable="true">
<kendo-grid-column *ngFor="let column of columns"
field="{{column.field}}"
title="{{column.title}}"
format="{{column.format}}"
filter="{{column.type}}">
</kendo-grid-column>
</kendo-grid>
</div>
dailyMachineNotes.component.ts
export class dailyMachineNotes{
public breakDownData: BreakDownDataModel[];
baseURL: string;
public columns: ColumnSetting[] = [
{ field: 'machineId', title: 'Machine Id',type: 'text'},
{ field: 'breakDownType', title: 'break Down Type', type: 'text' },
{ field: 'notes',title: 'Notes',type: 'text' },
{ field: 'startTime', format: '{0:yyyy-MM-dd HH:mm}',
title: 'Start Time', type: 'date' },
{ field: 'endTime',format: '{0:yyyy-MM-dd HH:mm}',
title: 'End Time',type: 'date' } ];
constructor(http: Http, #Inject('BASE_URL') baseUrl: string) {
this.http.get(baseUrl + 'dailyMachineNotes/GetdailyMachineNotes').subscribe(result => {
this.breakDownData = result.json() as BreakDownDataModel[];
}, error => console.error(error));
}
}
interface ColumnSetting {
field: string;
title: string;
format?: string;
type: 'text' | 'numeric' | 'boolean' | 'date';
}
BreakDownDataModel.ts
export const BreakDownDataModel= [
{ "machineId": 1, "breakDownType": "Change1",
"notes": test1, "startTime": 2018-04-13 09:05:00.000,
"endTime": 2018-04-13 09:45:00.000 },
{ "machineId": 2, "breakDownType": "Change2",
"notes": test2, "startTime": 2018-04-11 08:40:00.000,
"endTime": 2018-04-11 09:15:00.000 }
];
I am using a custom template for kendo grid popup Add / Edit form. Here is my working DEMO
I want to implement conditional validation on form fields such as if any value is entered for Address (not left empty) then the fields City and Postal Code should become required, otherwise they can be empty. Also I want to ise a custom validation rule for PostCode so that its length should always be equal to 4 else it should show a custom error message as "Postcode must be four digits"
I have referred these links:
Validation rules in datasource.model
Custom validation rules and error messages
but I can't figure out how can I implement validations in my datasource model?
Here is my code:
HTML:
<h3>I want to implement conditional validation on Add/Edit form such as if any value is entered for Address then the fields City and Postal Code should become required</h3>
<div id="grid"></div>
<script id="popup-editor" type="text/x-kendo-template">
<p>
<label>Name:<input name="name" required /></label>
</p>
<p>
<label>Age: <input data-role="numerictextbox" name="age" required /></label>
</p>
<p>
<label>Address: <input name="address"/></label>
</p>
<p>
<label>City: <input name="city"/></label>
</p>
<p>
<label>Post Code: <input name="postcode"/></label>
</p>
</script>
JS:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }]
});
If i were to do that, i would do these approach where
I will create a custom validator
Override the edit(grid) function place the validator there
Override the save(grid) function use validator.validate() before saving
Here is an example in dojo
basically this is the grid code:
var validator;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
save: function(e) {
if(!validator.data("kendoValidator").validate()){
e.preventDefault();
}
},
edit: function(){
validator = $("#test-form").kendoValidator({
validateOnBlur: false,
rules: {
matches: function(input) {
var requiredIfNotNull = input.data('test');
// if the `data-test attribute was found`
if (requiredIfNotNull) {
// get the input requiredIfNotNull
var isFilled = $(requiredIfNotNull);
// trim the values and check them
if ( $.trim(isFilled.val()) !== "" ) {
if($.trim(input.val()) !== ""){
// the fields match
return true;
}else{
return false;
}
}
// don't perform any match validation on the input since the requiredIf
return true;
}
// don't perform any match validation on the input
return true;
}
},
messages: {
email: "That does not appear to be a valid email address",
matches: function(input) {
return input.data("testMsg");
}
}
});
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }]
});
ps: i used to many if statement, you could simplify it i think
Here is the DEMO how I implemented it:
HTML:
<div id="grid"></div>
<script id="popup-editor" type="text/x-kendo-template">
<div id="myForm">
<p>
<label>Name:<input name="name" required /></label>
</p>
<p>
<label>Age: <input data-role="numerictextbox" name="age" required /></label>
</p>
<p>
<label>Address: <input name="address" id="address"/></label>
</p>
<p>
<label>City: <input name="city" id="city"/></label>
</p>
<p>
<label>Post Code: <input name="postcode" id="postcode"/></label>
<!--<span class="k-invalid-msg" data-for="postcode"></span>-->
</p>
</div>
</script>
JS:
var validator;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" },
{ field: "address" },
{ field: "city" },
{ field: "postcode" },
{ command: "edit" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30, address:'Addr', city:"city", postcode: '1234' },
{ id: 2, name: "John Doe", age: 33, address:'Addr11', city:"city11", postcode: '4321' }
],
schema: {
model: { id: "id" },
fields: {
name:{},
age:{},
address:{},
city:{},
postcode:{},
},
}
},
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html())
},
toolbar: [{ name: 'create', text: 'Add' }],
save: function(e) {//alert('save clicked');
if(!validator.validate()) {
e.preventDefault();
}
},
edit: function(e){
//alert('edit clicked');
validator = $("#myForm").kendoValidator({
messages: {
postcode: "Please enter a four digit Postal Code"
},
rules: {
postcode: function(input) {
//console.log(input);
if (input.is("[name='address']"))
{
if (input.val() != '')
{
$('#city, #postcode').attr('required', 'required');
//return false;
}
else
{
$('#city, #postcode').removeAttr("required");
}
}
else if (input.is("[name='postcode']")) {
if ($('#address').val() != '' && input.val().length != 4)
return false;
}
return true;
}
},
}).data("kendoValidator");
},
});
In Kendo UI (beta) for Angular 2, how does one trigger an event when a specific row is selected? There are no directives or components for the rows themselves; therefore, a (click)="triggeredFunction()" can't work if there is no row element.
Here is my grid:
<kendo-grid [data]="gridData" [selectable]="true">
<kendo-grid-column field="ProductName">
<template kendoHeaderTemplate let-column let-columnIndex="columnIndex">
{{column.field}}({{columnIndex}})
</template>
</kendo-grid-column>
<kendo-grid-column field="ProductName">
<template kendoCellTemplate let-dataItem>
<kendo-dropdownlist [data]="listItems"></kendo-dropdownlist>
</template>
</kendo-grid-column>
</kendo-grid>
Here is my component:
#Component({
selector: "ultron",
styleUrls: [String("./ultron.component.less")],
templateUrl: "./ultron.component.html",
})
export class UltronComponent {
private gridData: any[] = [{
"ProductID": 1,
"ProductName": "Chai",
"UnitPrice": 18.0000,
"Discontinued": true,
}, {
"ProductID": 2,
"ProductName": "Chang",
"UnitPrice": 19.0000,
"Discontinued": false,
}
}];
private listItems: Array<string> = ["#", "$", "#", "%"];
public triggeredFunction(){ ... }
}
The option that you need to set is selectable and the valid values are true and false as currently only single row selection is supported. So your grid should look like this
<kendo-grid
[data]="gridView"
[selectable]="true"
>
</kendo-grid>
For the event you need to attach a (selectionChange) event handler. Here is a plunkr
Selection in a Kendo UI enabled through the selectable option. The selected row index and selected state are provided through the selectionChange event. If you are also sorting or paging data in the grid then you will be bound to a GridDataResult. To get the bound item of the selected row in the grid, use the data property of the GridDataResult. See the following code sample:
import { Component } from '#angular/core';
import { GridDataResult, SelectionEvent } from "#progress/kendo-angular-grid";
import { SortDescriptor, orderBy } from "#progress/kendo-data-query";
#Component({
selector: 'my-app',
template: `
<kendo-grid [data]="gridDataResult" [selectable]="true" [height]="500"
[sortable]="true" (selectionChange)="selectedRowChange($event)"
[sort]="sort" (sortChange)="sortChange($event)">
<kendo-grid-column field="ProductID" title="Product ID" [width]="300"></kendo-grid-column>
<kendo-grid-column field="ProductName" title="Product Name"></kendo-grid-column>
<kendo-grid-column field="UnitPrice" title="UnitPrice"></kendo-grid-column>
<kendo-grid-column field="Discontinued" title="Discontinued"></kendo-grid-column>
</kendo-grid>
`
})
export class AppComponent {
public sort: SortDescriptor[] = [{ dir: "asc", field: "ProductID" }];
private gridDataResult: GridDataResult;
public products: any[] = [{
"ProductID": 1,
"ProductName": "Chai",
"UnitPrice": 18.0000,
"Discontinued": true,
}, {
"ProductID": 2,
"ProductName": "Chang",
"UnitPrice": 19.0000,
"Discontinued": false,
}
];
protected sortChange(sort: SortDescriptor[]): void {
this.sort = sort;
this.gridDataResult = {
data: orderBy(this.products, this.sort),
total: this.products.length
};
}
public selectedRowChange(selectionEvent: SelectionEvent) {
let selectedItem = this.gridDataResult.data[selectionEvent.index];
console.log(selectedItem);
}
}
Just addition to original answer which is still true except one change in plunker
It should say this.gridView.data[e.index]
If someone else comes to this page, can get the latest information.