Angular 2: Resetting form ignores initial value - forms

I have an Angular 2 app where I set default values for certain inputs like this:
this._stdSearchForm = this._formBuilder.group({
count: [{value: 50, disabled: false}, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern("^[0-9]+$")])]
});
I have inplemented a "reset" feature like this:
(click)="resetStdSearchForm()"
and that just runs:
this._stdSearchForm.reset();
That resets the form, but ignores the initial value defined in the FormBuilder group.
Is this behaviour intended?
Can I programatically set the value of "count" after resetting the form? I tried doing this:
this._stdSearchForm.value.count = 50;
but that changed nothing.

You can try the following:
this._stdSearchForm.setValue({ count: 50});
or you can do the same by:
this._stdSearchForm.reset({ count: 50});
The reset method resets the FormGroup. This means by default:
The group and all descendants are marked pristine
The group and all descendants are marked untouched
The value of all descendants will be null or null maps

Related

AG Grid Row-Grouping for showing version history of data

I'm a first time user of AG Grid and need some help identifying how to configure Row Grouping for my AG Grid in such a way that allows me to see my data group as a timeline/audit history. Was reading through the docs and haven't found an example on there that resembles what I'm looking for.
I have rowData that contains history and the visual expectation is that, the same base columnDefs assigned to the grid are used for the main "group" row (that contains the expand/collapse chevron) and all the expanded rows as well -- so there is no need for a "group column"
Anyone know how I can achieve this outcome? I have also looked at treeData and masterDetail but those didn't work out for me.
P.S. I don't rule out the possibility that I could be misreading/misunderstanding the AG Grid docs so any help there is appreciated.
EDIT: After fiddling around with things further, I believe I'm looking for a combination of two things:
The isRowMaster to enable expand/collapse on the main parent entry.
The groupDisplayType="groupRows" setting (minus the default row group cell because that would be handled by my master row from Point 1 instead)
After much head banging, turns out the solution was to use treeData. What I ended up creating was treeData containing only one level children.
Parent Node (expand/collapse)
child 1
...
child n
The other key was understanding how to structure your rowData and returning the proper dataPath to feed into the getDataPath handler for treeData. AG Grid expects a flat-list for rowData -- I say this as I was not able to get things working when having a nested tree structure like the following.
const mainRecord = {
id: "abc"
foo: 1,
bar: 2,
history: [
{ foo: 3, bar: 4 },
{ foo: 5, bar: 6 }
]
}
I had to modify my data structure above to return the history items as a flat list alongside the main record that I eventually sent as rowData. The other thing I had to do was add some hierarchy property to my objects to denote its placement in the tree. The hierarchy value is what I supplied to getDataPath
const rowData = [
{ id: "abc", foo: 1, bar: 2, hierarchy: ["abc"] }, // parent
{ foo: 3, bar: 4, hierarchy: ["abc", "34"] }, // child 1
{ foo: 5, bar: 6, hierarchy: ["abc", "56"] }, // child 2
]
After doing the above changes, I was able to get the expected visual outcome I was looking for. I think the big takeaway I got from this is as a first time user of AG Grid is, let it take care of grouping of your data on your behalf (as opposed to doing it yourself via structuring your models with some internal nested children structure)

Ag-Grid Server Side Row Group Key Creator

When using Ag-Grid's server side row model, I am unable to send a custom group key to the server in order to do proper group by queries.
My row data is a simple JSON structure but with one composite object.
row = {
athlete: '',
age: '',
country: {
name: 'Ireland',
code: 'IRE'
},
...
}
I am using the server side row model. To get the grid to display the country name is simple enough as I use the following column definition.
{
headerName: "Country",
colId: "country",
valueGetter: "data.country.name",
enableRowGroup: true
}
However, when I group by the Country column ag-grid sends the groupKey as 'Ireland' from my example above. But I need the group key to be the country code, 'IRE'. I cannot figure out how to generate a groupKey when using the server-side row model.
I have seen the keyCreator method, but this only works for client-side row model. In addition, I have seen the Tree Data Mode which has a callback for getServerSideGroupKey(dataItem) but then callback only gets used when gridOptions.treeData = true and when the treeData option is set to true, a "Group" column is always displayed regardless if a grouping is happening or not. I tested this out by setting isServerSideGroup: function(dataItem) {return false;}
Any help would be appreciated.
I was able to solve this issue by using the dot notation for the column definition's field attribute and a custom cellRenderer.
{
headerName: "Country",
colId: "country",
field: "country.code",
enableRowGroup: true,
cellRenderer: function (params) {
return params.data.country.name;
}
}
This allowed me to display the correct data point from the custom object and when doing server side actions, ag-grid will send the datapoint contained within the field attribute.

tabulator number editor max and min not working

i tried to put max and min for number editor ,but it is not working as expected not validation
my code below
{ , title: "Grade", field: "grade", validator: "required", editor: "number", editorParams: { min: 10, max: 120, step: 1, } },
but it allowed all numbers with no validation ??
You only have a max and min set on the number editor, all this will do is stop you incrementing or decrementing out of the range, it still allows input of any other number, just like a normal number input would do.
You need to use the max and min validators for this, at the moment you are only using the required validator
so your validator property should look like this:
validator:["required", "min:10", "max:120"]
If you want to your max validator to have a variable maximum then you would need to use a custom validator function for this, in the example below you could change the maxValue variable to look up from a global variable thus allowing you to change it whenever you like:
//custom validator
var variableMax= function(cell, value, parameters){
var maxValue = 10;
return value <= maxValue;
}
//assign validator in column definition:
validator:["required", "min:10", {type:variableMax, parameters:{}}]

Angular form reset() doesn't sets controls to empty

I'm referring to Hero guide passing the object to empty all the fields in the model like this.
this.form.reset({
"firstName": "",
"lastName": "bzz",
"reporter": ""
});
The problem is that it only sets the fields that are non-empty, i.e. bzz in the sample above. I've tried with setValue(...) but that gave the same effect. Goolearching the issue gave rather nothing other than references to the Hero examples.
I also tried to use the following. Same effect as well.
this.form.get("firstName").patchValue("");
What am I missing?
Don't pass an object, and It will set all the form controls to null:
this.form.reset();
this.form.reset({
firstName: {value: '1', disabled: true}
})

Meteor methods and Mongo $inc non-number error

I'm going through the methods chapter of Your First Meteor Application by David Turnbull.
I have a method for updating a field in the database.
'modifyPlayerScore': function(selectedPlayer, scoreValue){
PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} });
}
and these methods are being called from event functions
'click .increment': function(){
var selectedPlayer = Session.get('selectedPlayer');
Meteor.call('modifyPlayerScore', selectedPlayer, 5);
},
'click .decrement': function(){
var selectedPlayer = Session.get('selectedPlayer');
Meteor.call('modifyPlayerScore', selectedPlayer, -5);
}
When I use this functions in the app, I see an error in Terminal
Exception while invoking method 'modifyPlayerScore' MongoError: Modifier $inc allowed for numbers only
I have used a console.log statement to print the scoreValue variable and it shows either 5 or -5. I have a feeling that this may be a string and not a number but I'm not sure how to fix this error. Thanks in advance for your help!
When you added the score to a player with :
PlayersList.insert({name: 'test', score:3});
I suppose, you could increase the score. But not anymore.
It's because you passed a text parameter instead of an integer.
When you add a player you should use parseInt():
PlayersList.insert({
name: name,
score: parseInt(score),
createdBy: Meteor.userId()
})
Now, it should work. Or you can use parseInt() to set score
You should change the Meteor.method to this.
On the $inc remove the 5 static and place the second argument (scoreValue).
The method should look like this.
modifyPlayerScore': function(selectedPlayer, scoreValue){
PlayersList.update(selectedPlayer, {$inc: {score: scoreValue} });
}
And now you can make the call like this.
Meteor.call('modifyPlayerScore', selectedPlayer, 5);
where 5 its now the scoreValue argument
UPDATE
I made this working MeteorPad check you have everything like this.
NEW METEORPAD
I made this meteor pad based on the gist, and everything its working.
I used parse int on the score within PlayerList.insert as suggested above by yoh and it works for new entries. The old entries for score are still saved as strings so increment and decrement do not work. Delete your old entries and start fresh, it should work.