I have this simple component in my app:
import {Select, MenuItem} from '#material-ui/core';
import {useEffect, useState} from 'react';
export const CountrySelection = ({
countries,
selectedCountry,
onChange,
id,
className = ''
})=>{
const [_selectedCountry, _setSelectedCountry] = useState(null);
useEffect(()=>{
_setSelectedCountry(selectedCountry);
}, [selectedCountry]);
return(
<Select
value={(_selectedCountry && _selectedCountry.label) || ''}
onChange={onChange}
id={id}
className={'selection ' + className}
inputProps={{
'data-testid':'country-selection'
}}
>
{countries.map((c)=><MenuItem
key={c.id}
value={c.label}
>{c.label}</MenuItem>
)}
</Select>
)
}
This is my test attempt. I want to test that component keeps correct value/visual state when I change to a different option in the Select component:
afterEach(cleanup);
const setup = () => {
const countries = [
{label: "Austria", id: 0, code: 'at'},
{label: "Denmark", id: 1, code: 'dk'},
{label: "Germany", id: 2, code: 'de'}
];
const defaultCountry = countries[0];
const utils = render(
<CountrySelection
countries={countries}
selectedCountry={defaultCountry}
id="country-selection"
onChange={()=>{}}
/>
);
return {
...utils,
}
}
test('country selection has correct number of options', async()=>{
const {getAllByRole, getByText, getByTestId} = setup();
const selectEl = document.querySelector('#country-selection');
fireEvent.mouseDown(selectEl);
const options = getAllByRole('option');
expect(options.length).toBe(3);
const choice2 = getByText('Denmark');
expect(choice2.innerHTML).toBe('Denmark<span class="MuiTouchRipple-root"></span>');
const choice3 = getByText('Germany');
expect(choice3.innerHTML).toBe('Germany<span class="MuiTouchRipple-root"></span>');
// how to change the value and query it?
fireEvent.click(choice3);
const selection = getByTestId('country-selection');
expect(selection.value).toBe('Germany'); // doesn't work, value is still "Austria"
})
How do I do this with Select component? I cannot use native={true} prop.
(I am typing here just so that Stack overflow posting validation is happy with ratio of code to other text. I will type as long as it doesn't let me post my question. Sorry, humans.)
If you just want to check if a country has been selected correctly you can use userEvent to select the option like a real user would:
import { screen } from '#testing-library/react';
test('country selection has correct number of options', async()=>{
// Check that the correct number of options are displayed
const options = screen.getAllByRole('option');
expect(options.length).toBe(3);
// Select Denmark
userEvent.selectOptions(screen.getByRole('combobox'), 'dk');
// Check that Denmark is the selected country
expect((screen.getByText('Denmark') as HTMLOptionElement).selected).toBe(true);
// Select Germany
userEvent.selectOptions(screen.getByRole('combobox'), 'de');
// Check that Germany is now the selected country
expect((screen.getByText('Denmark') as HTMLOptionElement).selected).toBe(true);
})
First off, let me admit to being a React newbie...
I want to set the value displayed and selected in this component after the first render (eg from a button)
Here's my test code (with imports etc removed)
$(function () {
const data = [
{
DataID: 1,
DataType: 'Data1'
},
{
DataID: 2,
DataType: 'Data2'
},
{
DataID: 3,
DataType: 'Data3'
},
{
DataID: 4,
DataType: 'Data4'
}
]
ReactDOM.render(
<SelectionsExample
options={data}
preset={[data[1]]}
/>,
document.getElementById('divExampleSelector')
)
});
function SelectionsExample(props) {
const [options, setOptions] = useState(props.options);
const [preset, setPreset] = useState(props.preset);
function handleSelect(s) {
console.log((s ? s.DataType : 'Nothing') + ' selected');
}
function handlePreset() {
let s = options[2];
console.log('Preset', s);
setPreset([s]);
}
return (
<>
<Typeahead
id="selections-example"
options={options}
defaultSelected={preset ?? []}
onChange={(s) => handleSelect(s[0])}
labelKey="DataType"
clearButton
placeholder="Choose a value..."
/>
<Button
onClick={handlePreset}
variant="outline-secondary">Preset </Button>
</>
)
}
On first render, all works fine with as expected the second item in my options list shown.
But when I click the 'Preset' button, handlePreset runs but nothing changes in the control. I would have expected the selection to change to value of options[2].
If I change the Typeahead prop 'defaultSelected' to 'selected', then the only item I can select is the one I pass in in the 'preset' prop.
What am I doing wrong?
Using defaultSelected makes the typeahead uncontrolled, and will only display a preset selection when the component mounts. Since you want to be able to change the preset later, you should use selected to make the typeahead controlled:
function SelectionsExample(props) {
const [selected, setSelected] = useState(props.preset);
function handleSelect(s) {
console.log((s[0] ? s[0].DataType : 'Nothing') + ' selected');
setSelected(s);
}
function handlePreset() {
let s = props.options[2];
console.log('Preset', s);
setSelected([s]);
}
return (
<>
<Typeahead
clearButton
id="selections-example"
labelKey="DataType"
onChange={handleSelect}
options={props.options}
placeholder="Choose a value..."
selected={selected}
/>
<button onClick={handlePreset}>
Preset
</button>
</>
);
}
Working sandbox: https://codesandbox.io/s/heuristic-haze-3vugt
I'm using b-form-select with server-side generated option tags:
<b-form-select :state="errors.has('type') ? false : null"
v-model="type"
v-validate="'required'"
name="type"
plain>
<option value="note" >Note</option>
<option value="reminder" >Reminder</option>
</b-form-select>
When no data is set for this field I want to auto-select the first option in the list.
Is this possible? I have not found how to access the component's options from within my Vue instance.
your v-model should have the value of the first option.
example
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: 'a',
options: [
{ value: null, text: 'Please select an option' },
{ value: 'a', text: 'This is First option' },
{ value: 'b', text: 'Selected Option' },
{ value: { C: '3PO' }, text: 'This is an option with object value' },
{ value: 'd', text: 'This one is disabled', disabled: true }
]
}
}
}
</script>
You can trigger this.selected=${firstOptionValue} when no data is set.
what if we don't know what the first option is. The list is generated?
if you have dynamic data, something like this will work.
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: [],
options: [],
};
},
mounted: function() {
this.getOptions();
},
methods: {
getOptions() {
//Your logic goes here for data fetch from API
const options = res.data;
this.options = res.data;
this.selected = options[0].fieldName; // Assigns first index of Options to model
return options;
},
},
};
</script>
If your options are stored in a property which is loaded dynamically:
computed property
async computed (using AsyncComputed plugin)
through props, which may change
Then you can #Watch the property to set the first option.
That way the behavior of selecting the first item is separated from data-loading and your code is more understandable.
Example using Typescript and #AsyncComputed
export default class PersonComponent extends Vue {
selectedPersonId: string = undefined;
// ...
// Example method that loads persons data from API
#AsyncComputed()
async persons(): Promise<Person[]> {
return await apiClient.persons.getAll();
}
// Computed property that transforms api data to option list
get personSelectOptions() {
const persons = this.persons as Person[];
return persons.map((person) => ({
text: person.name,
value: person.id
}));
}
// Select the first person in the options list whenever the options change
#Watch('personSelectOptions')
automaticallySelectFirstPerson(persons: {value: string}[]) {
this.selectedPersonId = persons[0].value;
}
}
I've just discovered ag-grid. I'm using it on angular2+ and loading data from api. One of fields is date, but its in ISO format. I've been trying to format it, is there any way to do it, is it possible to add pipe or some other way? Usually i do it like this {{ someISODate | date: 'dd.MM.yyyy HH:mm'}}. Do i really have to format it manually in component before displaying it? Also I was wondering if its possible to add two fields under one column. Why? Well i have column author, and in data that im getting from api i have author.firstname and author.lastname, and now I wanna display both fields in same column. Any hints or examples are more than welcomed.
columnDefs = [
{headerName: 'Datum kreiranja', field: 'createdAt' }, //<-- wanna format it
{headerName: 'Vrsta predmeta', field: 'type.name' },
{headerName: 'Opis', field: 'description'},
{headerName: 'Kontakt', field: 'client.name'},
{headerName: 'Autor', field: 'author.firstname'}, //<-- wanna display author.lastname in same cell
{headerName: 'Status', field: 'status.name'}
];
You can do this by using cellRenderer (or valueFormatter as pointed in the UPDATE) and moment library.
{
headerName: 'Datuk kreiranja', field: 'createdAt',
cellRenderer: (data) => {
return moment(data.createdAt).format('MM/DD/YYYY HH:mm')
}
}
If you don't want to use moment, then below is how you can do it.
cellRenderer: (data) => {
return data.value ? (new Date(data.value)).toLocaleDateString() : '';
}
For Author field as well,
cellRenderer: (data) => {
return data.author.firstname + ' ' + data.author.lastname;
}
Reference: ag-grid: Cell Rendering
UPDATE
As suggested by #Mariusz, using valueFormatter makes more sense in this scenario. As per documentation, Value Formatter vs Cell Renderer
value formatter's are for text formatting and cell renderer's are for
when you want to include HTML markup and potentially functionality to
the cell. So for example, if you want to put punctuation into a value,
use a value formatter, but if you want to put buttons or HTML links
use a cell renderer.
You can use valueFormatter
{headerName: 'Datuk kreiranja', field: 'createdAt', valueFormatter: this.dateFormatter},
Create a small function:
dateFormatter(params) {
return moment(params.value).format('MM/DD/YYYY HH:mm');
}
First of all thanks to Paritosh.
The issue I was facing is the date field I was receiving from API is on the below format
"endDateUTC":"2020-04-29T12:00:00",
I have followed Paritosh solution using cellrenderer along with moment library but the value was always formatted to today's date for some reason.
The below solution is using valueFormatter with moment library.
This is for Angular2+ version. The job is really simple
In your .ts file:
import * as moment from 'moment';
{
headerName: 'End Date',
field: 'endDateUTC',
minWidth: 80,
maxWidth: 100,
valueFormatter: function (params) {
return moment(params.value).format('D MMM YYYY');
},
},
And the output you will get is:
End date:
29 APR 2020
Please feel free to change the date format you need.
Hope this will be helpful to some one.
I just want to expand on Vishwajeet's excellent answer from April 2019. Here's how I would use his code, and which import commands would be required:
import { Component, OnInit, ViewChild, LOCALE_ID, Inject } from '#angular/core';
constructor(#Inject(LOCALE_ID) private locale: string)
{
}
columnDefs = [
{ headerName: 'Last name', field: 'lastName' },
{ headerName: 'First name', field: 'firstName' },
{ headerName: 'DOB', field: 'dob', cellRenderer: (data) => { return formatDate(data.value, 'd MMM yyyy HH:mm', this.locale); }},
{ headerName: 'Policy start', field: 'policyStartDate', cellRenderer: (data) => { return formatDate(data.value, 'd MMM yyyy HH:mm', this.locale); } },
{ headerName: 'Policy end', field: 'policyEndDate', cellRenderer: (data) => { return formatDate(data.value, 'd MMM yyyy HH:mm', this.locale); } }
]
And your agGrid would contain something like this:
<ag-grid-angular
class="ag-theme-material"
[rowData]="rowData"
[columnDefs]="columnDefs"
</ag-grid-angular>
This works really nicely, but I decided to move the date formatting into it's own cell renderer for a few reasons:
The code above will display null values as "1 Jan 1970 01:00"
You would need to repeat this code, plus the imports and #Inject, into any control which uses it.
It repeats the logic each time, so if you wanted to change the date format throughout your application, it's harder to do. Also, if a future version of Angular broke that date formatting, you'd need to apply a fix for each occurrence.
So, let's move it into it's own cell renderer.
My DateTimeRenderer.ts file looks like this:
import { Component, LOCALE_ID, Inject } from '#angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid-community';
import { formatDate } from '#angular/common';
#Component({
selector: 'datetime-cell',
template: `<span>{{ formatTheDate(params.value) }}</span>`
})
export class DateTimeRenderer implements ICellRendererAngularComp {
public params: ICellRendererParams;
constructor(#Inject(LOCALE_ID) public locale: string) { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
formatTheDate(dateValue) {
// Convert a date like "2020-01-16T13:50:06.26" into a readable format
if (dateValue == null)
return "";
return formatDate(dateValue, 'd MMM yyyy HH:mm', this.locale);
}
public onChange(event) {
this.params.data[this.params.colDef.field] = event.currentTarget.checked;
}
refresh(params: ICellRendererParams): boolean {
return true;
}
}
In my app.module.ts file, I need to import this Component:
import { DateTimeRenderer } from './cellRenderers/DateTimeRenderer';
#NgModule({
declarations: [
AppComponent,
DateTimeRenderer
],
imports: [
BrowserModule,
AgGridModule.withComponents([DateTimeRenderer])
],
providers: [],
bootstrap: [AppComponent]
})
And now, back in my Component which uses the agGrid, I can remove LOCALE_ID, Inject from this line:
import { Component, OnInit, ViewChild, LOCALE_ID, Inject } from '#angular/core';
..remove it from our constructor...
constructor()
{
}
..import our new renderer...
import { DateTimeRenderer } from './cellRenderers/DateTimeRenderer';
..and change the columnDefs to use the new renderer:
columnDefs = [
{ headerName: 'Last name', field: 'lastName' },
{ headerName: 'First name', field: 'firstName' },
{ headerName: 'DOB', field: 'dob', cellRenderer: 'dateTimeRenderer' },
{ headerName: 'Policy start', field: 'policyStartDate', cellRenderer: 'dateTimeRenderer' },
{ headerName: 'Policy end', field: 'policyEndDate', cellRenderer: 'dateTimeRenderer' }
]
frameworkComponents = {
dateTimeRenderer: DateTimeRenderer
}
And I just need to make sure my agGrid knows about this new frameworkComponents section:
<ag-grid-angular
class="ag-theme-material"
[rowData]="rowData"
[columnDefs]="columnDefs"
[frameworkComponents]="frameworkComponents" >
</ag-grid-angular>
And that's it.
Again, the nice thing about this is I can use this date formatter anywhere throughout my code, and all the logic is in one place.
It's just shocking that, in 2020, we actually need to write our own date formatting function for an up-to-date grid like agGrid... this really should've been included in the agGrid libraries.
For Angular, if you want to do this without moment.js you can try something like below:
import { Component, OnInit, Inject, LOCALE_ID } from '#angular/core';
import { formatDate } from '#angular/common';
#Component({
selector: 'app-xyz'
})
export class xyzComponent implements OnInit {
constructor( #Inject(LOCALE_ID) private locale: string ) {
}
columnDefs = [
{headerName: 'Submitted Date', field: 'lastSubmittedDate', cellRenderer: (data) => {
return formatDate(data.value, 'dd MMM yyyy', this.locale);
}];
}
This component is using format date of angular/common
(Working & Optimized solution for date formatting is here!)
Tested on Angular 8 with dynamic data where date is coming like 2019-11-16T04:00:00.000Z.
In Ag-grid if you use valueFormatter, then no need of including "field:'Order Date'".
Also following Ragavan Rajan's answer. So you need to install moment.js in your angular CLI.
Working code and installation is below:
//Install moment.js in angular 8 cli.(no need of --save in latest versions
npm install moment
//In your component.ts
import * as moment from 'moment';
//Inside your colDef of ag-grid
{
headerName: "Effective Date",
field: "effectiveDate",
valueFormatter: function (params){
return moment (params.value).format ('DD MMM, YYYY');
}
/*
* This will display formatted date in ag-grid like 16 Nov, 2019.
* field name's value is from server side.(column name).
*/
If you are using AdapTable then you can do it via their Format Column function which can be applied either at design-time or run-time. And there you can choose pretty much any DateTime format that you want.
https://demo.adaptabletools.com/style/aggridformatcolumndemo
if you have two subfields like "Start Date" and "End Date" then you are supposed to do like this:
{
headerName: "Date Range",
children: [
{
field: 'StartDate',
cellRenderer: (data) => {
return data ? (new Date(data.value)).toLocaleDateString() : '';
}
},
{
field: 'EndDate',
cellRenderer: (data) => {
return data ? (new Date(data.value)).toLocaleDateString() : '';
}
}
],
}
I'm Using Angular 10, And I achieved the date formatting by using cellRenderer and DatePipe
{
field: "fieldName",
cellRenderer: (res) => {
const datepipe : DatePipe = new DatePipe("en-US");
var x = datepipe.transform(res.data.fieldName.split('T')[0],"yyyy-MM-dd");
return x;
}
},
Split('T') is used because when you call the Api, date comes in this format
"2021-07-31T00:00:00.000Z".
Try this:
{
headerName: 'Order Date',
field: 'OrderDate',
valueFormatter: function (params) {
var nowDate = new Date(parseInt(params.value.substr(6)));
return nowDate.format("yyyy-mm-dd");
}
I am using this date picker for my Ionic app:
https://github.com/rajeshwarpatlolla/ionic-datepicker
Two of the options I have set seem to have no effect.
Even though I have set dateFormat: 'yyyy-MM-dd' the date in the datepicker is shown in the default format dd-MM-yyyy.
Even though I have set closeOnSelect: true, the date picker does not close on select and the set button is visible.
Here is my code:
app.controller('MyCtrl', function($scope, $state) {
$scope.datepickerObject = {
titleLabel: 'Title', //Optional
inputDate: new Date(), //Optional
mondayFirst: true, //Optional
//disabledDates: disabledDates, //Optional
templateType: 'popup', //Optional
to: new Date(),
callback: function (val) { //Mandatory
datePickerCallback(val);
},
dateFormat: 'yyyy-MM-dd', //Optional
closeOnSelect: true //Optional
};
var datePickerCallback = function (val) {
if (typeof(val) === 'undefined') {
// no date selected
} else {
$scope.datepickerObject.inputDate = val;
}
};
});
In order to customize the date format you need to specify that in your html file:
<ionic-datepicker input-obj="datepickerObject">
<button class="button"> {{datepickerObject.inputDate | date:'yyyy/MM/dd'}}</button>
</ionic-datepicker>
Also, in the current release- 0.9.0- closeOnSelect dosen't work.
https://github.com/rajeshwarpatlolla/ionic-datepicker/issues/110
Regards