Angular 2 checkbox - How to use [checked] with (ngModelChange)? - forms

I'm having trouble programmatically setting a checkbox in Angular 2. The following code fires onCheck() whenever the user checks the checkbox. I can also check the checkbox programmatically by setting this.select to 'true'.
<input type="checkbox" [(ngModel)]="v.checked" [checked]="select" (ngModelChange)="onCheck(v.checked)">
My problem is that when I set this.select to 'true', ngModelChange doesn't seem to detect the change and onCheck() doesn't fire... :-(
Any tips? Is there an alternative way to programmatically set a checkbox AND have its associated function fire?

you can use checkbox with component variable like :
#Component({
selector : 'my-component'
template : `<input type="checkbox" [(ngModel)]="selected"/>`
})
export class MyComponent(){
public selected: boolean = false;
}

Related

Angular focus on formcontrol

I have the following input:
<input
#participantInput="ngModel"
id="participantInput"
pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$"
class="cell small-7"
placeholder="John.Doe#gmail.com"
[(ngModel)]="newParticipantMail"
(keyup.enter)="addParticipant()"
style="height:10%;">
Due to the #participantInput="ngModel"
I'm not able to retrieve the elementRef like :
#ViewChild('participantInput') participantInput: ElementRef;
So, how can I set the focus on that field?
You can add another template variable like this:
<input
#participantInput="ngModel"
#participantRef
id="participantInput"
pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$"
class="cell small-7"
placeholder="John.Doe#gmail.com"
[(ngModel)]="newParticipantMail"
(keyup.enter)="addParticipant()"
style="height:10%;">
Then you can access it into your component
#ViewChild('participantRef') participantRef: ElementRef;
Obviously you must wait for view initialization, for example implementing AfterViewInit interface

Submit form array with Vue to Laravel

Before I started using Vue I had a simple form that would update 1 value on 1 column # 1 request at a time. Now I am using Vue and my form has a new 'middle' button that is being used to build up an array of items to submit 1 request to update multiple columns dynamically.
Problem is now that prevent default is enabled, my original form submission no longer works and I need to either submit the request with Vue or is there a way to re-enable default action on a button? This would be great.
<form #submit.prevent="newbutton">
// new button
<button #click="newbutton"></button>
// original button
<button #click="submit" :id="{{ $element->id }}></button> // #submit.enableDefault ??
The prevent is just a helper method on the #submit. To allow this variance you will need to move the logic into your newbutton method
// in template remove prevent
<form #submit="newbutton" action="/where-this-should-post">
// in script move logic to your newbutton method
methods {
newbutton(event) {
if (formNotValid) {
event.preventDefault()
}
}
}

TextField is not getting updated on re-render with different intialValues

I'm using redux-form-material-ui for the forms. I have simple form with two text fields. This form will show the initalValues passed to it and user can also update the values of TextField. These TextFields working fine with validations and all but I'm facing problem while re-rendering. On route change, I'm passing the different intialValues to that form component but even though proper values passed to it, TextFields are not getting updated. It just shows the first time passed initialValues.
Here is my code:
From parent component:
<ReduxForm {...initialValues} />
ReduxForm component:
class ReduxForm extends React.Component {
render () {
return (
<div>
<form onSubmit={() => console.log('Submitted')} >
<Field
className='input-field'
name='name'
component={TextField}
floatingLabelText='Full Name'
/>
<Field
className='input-field'
name='email'
component={TextField}
floatingLabelText='Email'
/>
</form>
</div>
)
}
}
export default reduxForm({
form: 'test-form',
validate
})(ReduxForm)
I Know that, this is the same problem with defaultValue in material-ui's TextField. Is this expected behavior in redux-form-material-ui also? If so, is there way I can solve this issue without setting the state and all?
Thank you!
Haven't used redux-form-material-ui but try adding enableReinitialize: true to your reduxForm decorator
export default reduxForm({
form: 'test-form',
validate,
enableReinitialize: true
})(ReduxForm);
And see if that works.

How do I bind a value to a textbox in Angular2?

I have been trying to figure out how to bind a value to a textbox in Angular2. Currently I have a textbox with a placeholder that is loaded with a predetermined value.
<input id="textbox" class="k-textbox" placeholder={{label}} />
But once I change a value of a date component, I would want the placeholder value to be updated to the date value selected. So far i wrote this but this doesn't seem to be working. Please advice.
date-component.html
<input id="datepicker" (input)="changeLabel()"/>
date-component.ts
label:string;
constructor() {
this.label = 'Select Date';
}
changeLabel() {
this.label = 'Date Selected';
}
}
use an click event to propagate the changes.
date-component.html
<input id="datepicker" (click)="changeLabel()"/> //<-- click event
You could use two way databinding with NgModel.
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel
Basically this would make "label" change to whatever the user types.
<input [(ngModel)]="label" id="datepicker" />
You will also need to import FormsModule in your app.
Plunker to show what I mean:
https://plnkr.co/edit/CfmalT7GesrP5lzBsNFx?p=preview
use keyup Event
<input (keyup)="changeLabel()">
enter the value its call the keyup event

Adding Bootstrap 3 popover breaks JQuery Validation Plugin

I have a form, which I'm validating using JQuery Validation plugin. Validation works file until I add a Bootstrap 3 popover to the text field with name "taskName" (the one being validated) (please see below) . When I add the popover to this text field, error messages are repeatedly displayed every time the validation gets triggered. Please see the code excerpts and screenshots below.
I've been trying to figure out what is happening, with no success so far. Any help will be greatly appreciated. Thanks in advance!
HTLM Excerpt
The popover content
<div id="namePopoverContent" class="hide">
<ul>
<li><small>Valid characters: [a-zA-Z0-9\-_\s].</small></li>
<li><small>Required at least 3 characters.</small></li>
</ul>
</div>
The form
<form class="form-horizontal" role="form" method="post" action="" id="aForm">
<div class="form-group has-feedback">
<label for="taskName" class="col-md-1 control-label">Name</label>
<div class="col-md-7">
<input type="text" class="form-control taskNameValidation" id="taskName" name="taskName" placeholder="..." required autocomplete="off" data-toggle="popover">
<span class="form-control-feedback glyphicon" aria-hidden="true"></span>
</div>
</div>
...
</form>
JQuery Validate plugin setup
$(function() {
//Overwriting a few defaults
$.validator.setDefaults({
errorElement: 'span',
errorClass: 'text-danger',
ignore: ':hidden:not(.chosen-select)',
errorPlacement: function (error, element) {
if (element.is('select'))
error.insertAfter(element.siblings(".chosen-container"));
else
error.insertAfter(element);
}
});
//rules and messages objects
$("#aForm").validate({
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
},
success: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
});
$('.taskNameValidation').each(function() {
$(this).rules('add', {
required: true,
alphanumeric: true,
messages: {
required: "Provide a space-separated name."
}
});
});
});
Bootstrap 3 popover setup
$('[data-toggle="popover"]').popover({
trigger: "focus hover",
container: "body",
html: true,
title: "Name Tips",
content: function() { return $('#namePopoverContent').html();}
});
The screenshots
First Edit
It seems I did not make my question clear, so here it goes my first edit.
I'm not using the popover to display the error messages of the validation. The error messages are inserted after each of the fields that fail validation, which is precisely what I want. Hence, this question does not seem to be a duplicate of any other question previously asked.
Regarding the popover, I just want to add an informative popover that gets displayed whenever the user either clicks the text field "taskName" or hovers the mouse over it. Its role is completely independent of the validation.
The question is, then, why adding the (independent) popover is making the validation plugin misbehave, as shown in the screenshots.
I had the very same issue a few days ago and the only solution I found was to use 'label' as my errorElement:.
Change the line errorElement: 'span' to errorElement: 'label' or simply removing the entire line will temporarily fix the issue. ('label' is the default. )
I am not completely sure what the JQ validate + BS popover conflict is, but I will continue to debug.
After some debugging I think I found the issue.
Both jQuery validate and bootstrap 3 popovers are using the aria-describedby attribute. However, the popover code is overwriting the value written by jQuery validate into that attribute.
Example: You have a form input with an id = "name", jQuery validate adds an aria-describedby = "name-error" attribute to the input and creates an error message element with id = "name-error" when that input is invalid.
using errorElement:'label' or omitting this line works because on line 825 of jquery.validate.js, label is hard-coded as a default error element selector.
There are two ways to fix this issue:
Replace all aria-describedby attributes with another attribute name like data-describedby. There are 4 references in jquery.validate.js. Tested.
or
Add the following code after line 825 in jquery.validate.js. Tested.
if ( this.settings.errorElement != 'label' ) {
selector = selector + ", #" + name.replace( /\s+/g, ", #" ) + '-error';
}
I will also inform the jQuery validate developers.
The success option should only be used when you need to show the error label element on a "valid" element, not for toggling the classes.
You should use unhighlight to "undo" whatever was done by highlight.
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
$(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
(The success option could also be used in conjunction with the errorPlacement option to show/hide tooltips or popovers, just not to do the styling, which is best left to highlight and unhighlight.)
Also, I recommend letting the Validate plugin create/show/hide the error label element, rather than putting it the markup yourself. Otherwise, the plugin will create its own and ignore the one you've created.
In case you were unaware, you cannot use the alphanumeric rule without including the additional-methods.js file.