What is the right way to bind 2 angular 2 form controls together - angular2-forms

I want to hook up 2 input controls to each other, so when one changes, it updates the other. As an example, its 2 percentage fields, if I set one to 80, the other will get set to 20 to balance it to total 100.
Both inputs are in a form group, so I feel like I should use these and methods on these to subscribe to value changes and not touch native elements or events.
Can anyone suggest the base way to go about it?

You can subscribe to valueChanges for that particular formControlName.
For example in your controller you can do
this.myForm.get('firstControl').valueChanges.subscribe(val => {
this.myForm.patchValue({
secondControl:100-val
});
});
You should repeat the same to listen when the second control changes.
Remember to validate with max values too i.e set maximum to 100.

A simple way would be to use the ngModelChange event emitted by one input field to update the other.
In the code below it updates input #2 when input #1 changes, and vice versa.
Input 1: <input type="text" [(ngModel)]="first" (ngModelChange)="second = 100 - first" />
Input 2: <input type="text" [(ngModel)]=second (ngModelChange)="first = 100 - second"/>
Note: this is pretty basic, all inline, but in your example you'd want to add some error handling for non-numeric characters, range values > 100 etc. So you might want to define the handler for ngModelChange in your components definition (presumably in typescript) rather than in the template like I've done here.

I'm using angular reactive forms and was able to create a component that binds to the form FormGroup and the names of the controls, like this:
<app-percentage-balance
[formGroup]="form"
firstControlName="firstControl"
secondControlName="firstControl">
in my component I have:
#Input() formGroup: FormGroup;
#Input() firstControlName: string;
#Input() secondControlName: string;
public ngOnInit(): void {
this.firstControl = this.formGroup.controls[this.firstControlName] as FormControl;
this.secondControl = this.formGroup.controls[this.secondControlName] as FormControl;
this.firstControl.statusChanges.subscribe((status) => {
if (status == "VALID") {
// do stuff
}
});
this.secondControl.statusChanges.subscribe((status) => {
if (status == "VALID") {
// do stuff
}
});
}

Related

Angular Directive for validating latitude and longitude

I am working with an application which generates different kind of reports.
In couple of reports, we are using Longitude/Latitude as an input box. We need to put some validation logic for Latitude/Longitude e.g The latitude must be a number between -90 and 90 and the longitude between -180 and 180.
So what is the best-fit approach for that? Shall I create a Directive for same or any other idea?
In case of Directive if some can share some code then it's helpful.
Depends on how you wish to handle this... technically, HTML5 already can do that
<input type="number" name="longtitude" min="-180" max="180">
<input type="number" name="latitude" min="-90" max="90">
But you can of course use a directive, if you have more fields that you want to restrict in terms of upper and lower limits. It has several benefits while doing this. We can exert more control about how our components are used. The pure HTML5 solution has the drawback, that you can still input numbers that are greater than those.
EDIT: I also created a directive for you, that looks somewhat like this in the HTML Template...
<input #inputReference appNumberRange [inputRefObject]="{inputRef: inputReference, minValue: -180, maxValue: 180}" type="number"
placeholder=" - Longitude- ">
So, what happened here? I created a directive with the name NumberRange, which has the input parameter "inputRefObject" that takes a template variable #inputReference in this case, the min and max value.
But now let's go to the directive...
import { Directive, HostListener, Input } from '#angular/core';
#Directive({
selector: '[appNumberRange]'
})
export class NumberRangeDirective {
constructor() { }
#Input() inputRefObject: {inputRef: any, minValue: number, maxValue: number};
#HostListener('keyup', ['$event'])
restrictNumberRange() {
const {inputRef, minValue, maxValue} = this.inputRefObject;
if(inputRef.value > maxValue) {
inputRef.value = maxValue;
} else if(inputRef.value < minValue) {
inputRef.value = minValue
} else {
// Do nothing, or perhaps do something else...
return;
}
}
}
It's kept rather simplistic and I wouldn't vouch for best practices here, but it should do what you wish it to do.
We use the hostlistener on the object we're using the keyup event on. Technically, I wouldn't even need to pass the event in the HostListener arguments, but I left it there in case you needed it.
But yeah, if the number is larger than the maxnumber, the value in the input is changed to the highest allowed input and vice versa for the lowest number. From there you can basically expand the way you like. You could perhaps check if the inputs are actually only of the number type! You could check the value the moment something is pasted into the input and so forth

knockoutJS checkbox and textbox working together

I have a checkbox and a textbox (both are enabled and the checkbox starts unchecked [false]).
What I need is the following:
When I write something in the textbox and leave it (loses focus) the
checkbox is checked automatically.
When I write something in the
textbox, remove it and leave it the checkbox should remain
unchecked.
When I write something in the textbox and click the
checkbox, the checkbox is checked now and the data in the textbox is
not cleared.
When I write something in the textbox and click the
checkbox twice, first happens step 3 and then the checkbox is
unchecked and the data in the textbox is cleared.
When I click in the checkbox the checkbox is checked, then I write in the textbox
and uncheck the checkbox, then the data in the textbox is cleared.
What I tried so far is the following code:
//The checked property in the checkbox is binded to
that.BuildingCriteria.IncludeLoadingDocks
that.BuildingCriteria.IncludeLoadingDocks.subscribe(function (newValue) {
if (!that.updatingTextBox && !newValue) {
that.BuildingCriteria.LoadingDocksMin(null);
}
});
//The textbox value is binded to that.BuildingCriteria.LoadingDocksMin
that.BuildingCriteria.LoadingDocksMin.subscribe(function (newValue) {
that.updatingTextBox = true;
that.BuildingCriteria.IncludeLoadingDocks(true);
that.updatingTextBox = false;
});
This works if you try all the steps above, for all of them but then, when you try some of them again stops working for some... specially if you write something in the textbox with the checkbox unchecked and then leave the textbox, it doesn't check the checkbox automatically anymore.
I tried using flags as you can see but I couldn't make it to work on ALL the cases ALWAYS.
I've been working on this for days so if you can help me out soon I'd appreciate it a lot!
Thanks in advance!!
It's near impossible to gave a straight up answer to your question, but from it I feel the closest thing may be to note a few KO features that you may yet need to consider.
The value binding supports a valueUpdate = 'afterkeydown' version, which would allow you to keep your textbox and checkbox in synch real time. This may well remove the need for requirement 3.
The computed observable supports specializing read and write operations, which at times may be clearer than using subscriptions.
You may need to introduce a "grace" period for the checkbox, if you must stick with requirement 3. Just don't allow updating the checkbox too shortly after leaving the textbox. The throttle extender and hasfocus binding can help you with that.
There's a great blogpost on when to use which feature.
In any case, your requirements are a bit hard to understand without the business case, and it might even be that you're experiencing an XY-problem. From your implementation requirements I'd assume functional (not implementation) requirements like this:
There's a textbox to hold the actual order/criterium/name/whatever.
There's a checkbox to indicate such an order/etc is wanted.
This checkbox should be in synch (checked) with whether the user typed some text.
This checkbox should be in synch (unchecked) if the user empties the textbox.
If the user checks the checkbox then
If there was text for the order/etc it should be cleared.
If there was no text a default order/etc should be suggested.
Here's a jsfiddle with a demo of how you could approach these functional requirements. For completeness, here's the relevant code, starting with the View:
<input type="checkbox" data-bind="checked: isChecked" />
<input type="textbox" data-bind="value: someText, valueUpdate: 'afterkeydown', selectSuggestion: someText" />
The custom binding for selecting the "default suggestion text":
var suggestion = "<enter something>";
ko.bindingHandlers.selectSuggestion = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var currentText = ko.utils.unwrapObservable(valueAccessor());
if (currentText === suggestion) element.select();
}
};
And the ViewModel:
var ViewModel = function() {
var self = this;
var privateIsChecked = ko.observable(false);
var privateText = ko.observable("");
self.isChecked = ko.computed({
read: privateIsChecked,
write: function(value) {
if (!privateIsChecked() && value && privateText() === "") {
privateText(suggestion);
}
if (privateIsChecked() && !value) {
privateText("");
}
privateIsChecked(value);
}
});
self.someText = ko.computed({
read: privateText,
write: function(value) {
privateIsChecked(value !== "");
privateText(value);
}
});
}
I'm aware that this doesn't directly answer your question, but like I said that's pretty hard to do for us on Stack Overflow, without knowledge of your business case.

Event listener for multiple elements - jQuery

In the ASP MVC page I'm currently working on, the values of three input fields determine the value of a fourth. Zip code, state code, and something else called a Chanel Code will determine what the value of the fourth field, called the Territory Code, will be.
I just started learning jQuery a couple weeks ago, so I would first think you could put a .change event that checks for values in the other two fields and, if they exists, call a separate method that compares the three and determines the Territory code. However, I'm wondering if there is a more elegant way to approach this since it seems like writing a lot of the same code in different places.
You can bind a callback to multiple elements by specifying multiple selectors:
$(".field1, .field2, .field3").click(function() {
return field1 +
field2 +
field3;
});
If you need to perform specific actions depending on which element was clicked, another option would be to create a function which performs the actual computation and then invoke that from each callback.
var calculate = function() {
return field1 +
field2 +
field3;
};
And then invoke this function when on each click:
$(".field1").click(function() {
// Perform field1-specific logic
calculate();
});
$(".field2").click(function() {
// Perform field2-specific logic
calculate();
});
// etc..
This means that you do not repeat yourself.
This works for me
jQuery(document).on('scroll', ['body', window, 'html', document],
function(){
console.log('multiple')
}
);
Adding another possibility, just in cased this may help someone. This version should work on dynamically created fields.
$("#form").on('change', '#Field1, #Field2, #Field3', function (e) {
e.preventDefault();
console.log('something changed');
});

ASP.NET MVC: Tri-state checkbox

I'm just now starting to learn ASP.NET MVC. How would I go about creating a reusable tri-state checbox? In WebForms this would be a control, but I don't know the MVC equivalent.
Add a TriStateCheckBox (or TriStateCheckBoxFor if you use the strongly typed overloads) extension method to HtmlHelper and add the namespace of that extension method class to the namespaces section of your web.config.
As for the implementation, I'd recommend having at look at the InputExtensions source on codeplex and using that to create your own.
Limitations:
View Rendering - When rendering HTML content, there is no attribute you can possibly place on an <input type="checkbox" /> that will give it the property indeterminate.
At some point, you'll have to use JavaScript to grab the element and set the indeterminate property:
// vanilla js
document.getElementById("myChk").indeterminate = true;
// jQuery
$("#myCheck).prop("indeterminate", true);
Form Data - model binding will always be limited to what values are actually sent in the request, either from the url or the data payload (on a POST).
In this simplified example, both unchecked and indeterminate checkboxes are treated identically:
And you can confirm that for yourself in this Stack Snippet:
label {
display: block;
margin-bottom: 3px;
}
<form action="#" method="post">
<label >
<input type="checkbox" name="chkEmpty">
Checkbox
</label>
<label >
<input type="checkbox" name="chkChecked" checked>
Checkbox with Checked
</label>
<label >
<input type="checkbox" name="chkIndeterminate" id="chkIndeterminate">
<script> document.getElementById("chkIndeterminate").indeterminate = true; </script>
Checkbox with Indeterminate
</label>
<label >
<input name="RegularBool" type="checkbox" value="true">
<input name="RegularBool" type="hidden" value="false">
RegularBool
</label>
<input type="submit" value="submit"/>
</form>
Model Binding - Further, model binding will only occur on properties that are actually sent. This actually poses a problem even for regular checkboxes, since they won't post a value when unchecked. Value types do always have a default value, however, if that's the only property in your model, MVC won't new up an entire class if it doesn't see any properties.
ASP.NET solves this problem by emitting two inputs per checkbox:
Note: The hidden input guarantees that a 'false' value will be sent even when the checkbox is not checked. When the checkbox is checked, HTTP is allowed to submit multiple values with the same name, but ASP.NET MVC will only take the first instance, so it will return true like we'd expect.
Render Only Solution
We can render a checkbox for a nullable boolean, however this really only works to guarantee a bool by converting null → false when rendering. It is still difficult to share the indeterminate state across server and client. If you don't need to ever post back indeterminate, this is probably the cleanest / easiest implementation.
Roundtrip Solution
As there are serious limitations to using a HTML checkbox to capture and post all 3 visible states, let's separate out the view of the control (checkbox) with the tri-state values that we want to persist, and then keep them synchronized via JavsScript. Since we already need JS anyway, this isn't really increasing our dependency chain.
Start with an Enum that will hold our value:
/// <summary> Specifies the state of a control, such as a check box, that can be checked, unchecked, or set to an indeterminate state.</summary>
/// <remarks> Adapted from System.Windows.Forms.CheckState, but duplicated to remove dependency on Forms.dll</remarks>
public enum CheckState
{
Checked,
Indeterminate,
Unchecked
}
Then add the following property to your Model instead of a boolean:
public CheckState OpenTasks { get; set; }
Then create an EditorTemplate for the property that will render the actual property we want to persist inside of a hidden input PLUS a checkbox control that we'll use to update that property
Views/Shared/EditorTemplates/CheckState.cshtml:
#model CheckState
#Html.HiddenFor(model => model, new { #class = "tri-state-hidden" })
#Html.CheckBox(name: "",
isChecked: (Model == CheckState.Checked),
htmlAttributes: new { #class = "tri-state-box" })
Note: We're using the same hack as ASP.NET MVC to submit two fields with the same name, and placing the HiddenFor value that we want to persist first so it wins. This just makes it easy to traverse the DOM and find the corresponding value, but you could use different names to prevent any possible overlap.
Then, in your view, you can render both the property + checkbox using the editor template the same way you would have used a checkbox, since it renders both. So just add this to your view:
#Html.EditorFor(model => model.OpenTasks)
The finally piece is to keep them synchronized via JavaScript on load and whenever the checkbox changes like this:
// on load, set indeterminate
$(".tri-state-hidden").each(function() {
var isIndeterminate = this.value === "#CheckState.Indeterminate";
if (isIndeterminate) {
var $box = $(".tri-state-box[name='" + this.name + "'][type='checkbox']");
$box.prop("indeterminate", true);
}
});
// on change, keep synchronized
$(".tri-state-box").change(function () {
var newValue = this.indeterminate ? "#CheckState.Indeterminate"
: this.checked ? "#CheckState.Checked"
: "#CheckState.Unchecked";
var $hidden = $(".tri-state-hidden[name='" + this.name + "'][type='hidden']");
$hidden.val(newValue);
});
Then you can use however you'd like in your business model. For example, if you wanted to map to a nullable boolean, you could use the CheckState property as a backing value and expose/modify via getters/setters in a bool? like this:
public bool? OpenTasksBool
{
get
{
if (OpenTasks == CheckState.Indeterminate) return null;
return OpenTasks == CheckState.Checked;
}
set
{
switch (value)
{
case null: OpenTasks = CheckState.Indeterminate; break;
case true: OpenTasks = CheckState.Checked; break;
case false: OpenTasks = CheckState.Unchecked; break;
}
}
}
Alternative Solution
Also, depending on your domain model, you could just use Yes, No, ⁿ/ₐ radio buttons
ASP.NET MVC certainly doesn't provide such component, actually it simply relies on the standard elements available in HTML but you may want to check out this solution.

Grails: How do I make a g:textfield to load some data and display it in other g:textfield?

I have two g:textfields
in the first one I should write a number lets say 12 and in the g:textfield next to it it should load the predetermined name for number 12.
The first one is named 'shipper' and the other 'shipperName'
Whenever I write the code 12 in the 'shipper' txtfield, it should return the name of the shipper in the 'shipperName' box.
Thanks in advance!
Examples:
If I write the number 12 it should return USPS
http://i53.tinypic.com/2i90mc.jpg
And every number should have a different 'shipperName'
Thanks again!
That's quite easy if you'll use jQuery. Check out the event handlers ("blur" is the one you want which occurs when the user leaves the numerical box).
For example:
$("#shipper").blur(function() {
$("#shipperName").load(
"${createLink(controller: 'shipper', action: 'resolveShipper')}?id=" +
$("#shipper").val()
);
});
The $(this).val() at the end is the value of the input field the user just left.
And the "ShipperController.resolveShipper" action would look something like this:
def resolveShipper = {
render text: Shipper.get(params.id).name, contentType: "text/plain"
}
There are other things you might want to do, like automatically filling in the shipperName field as the user types without leaving the edit field, probably after a delay. However the event handler stays the same, just the event is changing (from "blur" to "change" or something like this)
To relate two strings, it's easiest to use an object to create a dictionary/ map, as shown below;
$('#input1').bind('keyup',function() {
var map = {
"1":"One",
"2":"Fish",
"3":"Bar"
};
$('#input2').val(map[$(this).val()]);
});
You can see this in action here: http://www.jsfiddle.net/dCy6f/
If you want the second value only to update when the user has finished typing into the first input field, change "keyup" to "change".

Resources