Fire ng change on change of checkbox checked value in angular 8 - html

Changed the value but change event is not getting triggered.I want to trigger the change when ischecked is changed
in html
<input class="inputStyle" type="checkbox" [checked]="isChecked" id="actA" tabindex="0" (change)="onAct($event)">
have another function(in ts)
onChangeoption(lang) {
this.isChecked = true; `enter code here`
}

What you are trying to do is trigger a change event after you have programatically changed the value of the input first and this is not going to work.
I can suggest two approaches:
Approach 1:
From what you have shown in those snippets, it seems easy to call onAct inside the onChangeoption. If you don't really need the change event object, you can call onAct immediately after you change the value of isChecked.
Approach 2:
If you need the change event object, create a reference of the input element and programatically dispatch a change event
In your TypeScript code:
#ViewChild('myCheckbox') myCheckbox;
onChangeoption() {
this.isChecked = true; `enter code here`
this.myCheckbox.nativeElement.dispatchEvent(new Event('change'));
}
And update your template:
<input #myCheckbox class="inputStyle" type="checkbox" [checked]="isChecked"
id="actA" tabindex="0" (change)="onAct($event)">

Related

Changing edited textbox value to the original passed value on clicking outside the div of textbox in reactJS

Please refer the image attached first by clicking on here.
There is a textbox which retrieves the original value from the state. Now, if any user changes textbox's value and click's outside the div then the textbox value must be replaced with the original value obtained from the state i.e 2000 here. If the user clicks on edit after changing the value in the textbox then that value must be updated in the state.
Any suggestions to perform this task.
Code sample is appreciated.
Thank you in advance.
I had the same issue. I found the solution that outside div onClick event you set state to original value and input div add onclick event stopPropagation so click on this div outside onClick event not called and edit button add onclick or onSubmit(if you use form) event for perform edit login.
Sample code is here.
this.state = {
flag: false,
number: 0,
oldNumber: 0
}
handleEditMaxAmount =()=>{
// edit code here.
}
outClickHandle =()=>{
if(this.state.flag){
this.setState({
number: oldNumber
})
this.state.flag = false
}
}
inClickHandle =()=>{
this.state.flag = true;
}
<div onClick={this.outClickHandle}>
...
<div onClick={(e)=>{e.stopPropagation();}}>
<input type="number" value={this.state.number} onChange={this.inClickHandle} name="number" />
<button onClick={this.handleEditNumber}>Edit </button>
</div>
...
</div>

How to trigger ngModelChange with a button in Angular 2

I use *ngFor to populate my table.
<tr *ngFor= "stu in students">
<td>{{stu.name}}</td>
<td><input type="checkbox" ngModel="isChecked"
(ngModelChange)="addID(stu.id)</td>
</tr>
Then I have a button outside the table.
<button (click)="selectAllID()">select all</button>
Then I have my component as:
studentID=[];
isChecked=false;
addID(id:number){
this.student.push (id);
//I do other thing with id
}
selectAllID (){
If (this.isChecked)
this isChecked = false;
else this isChecked = true
}
The problem is:
if I check individual checkbox, the addID() function is executed. But if I click on the select all button, the checkboxes get selected. But the addID() function is not called.
How can I trigger the ngModelChange function when I use the select all button so I get all selected id's
You have only one way binding of the input control with ngModelChange directive. But to update the view you should bind the control to ngModel.
<input type="checkbox" [ngModel]="isChecked"
(ngModelChange)="addID(stu.id)">
Thank you everyone. i finally resolved the issue. This is what i did:
I used the selectAll() function to automatically load all id's (this id i get from the source loading my tables) to an array. and
i set the value of isChecked to true or false.

Angular 2 html form validation

I've created a form using html validations with Angular 2.
I want to to check the sate of the inputs (no empty, correct format, etc) when the user click to a certain button. At the moment I'm doing it as following:
<form id="memberForm" #memberForm="ngForm" >
<input
type="text"
id="MemberName"
required
name="MemberName"
[(ngModel)]="newMember.name">
</form>
<div
[ngClass]="{'button_disabledButton' : !memberForm?.valid}"
(click)="onSubmit(memberForm?.valid, memberForm);">
<span>Next</span>
</div>
With this, I'm only evaluating the input once clicked and focus out. How can I make it hapens when the user click in the "Next" element?
You should make getter/setter solution for your ngModel input.
In the .ts file in the appropriate class put this:
savedVar:string = '';
get variable(): string {
return this.savedVar;
}
set variable(str: string) {
this.savedVar = str;
// do your validation
}
In template use ngModel=variable like this:
<input [(ngModel)]="variable">

Launch an event when checking a checkbox in Angular2

I'm newbie in Angular2 and in web globally , I want to launch an action that changes an oject paramater value in the Database when checking a checkbox and or unchecking it using Material-Design, I tried with [(ngModel)] but nothing happened. the idea is that i have to add some propositions with checked | unchecked status to tell if it is a true or false proposition. Here is the proposition model
export class PropositionModel {
id:string;
wordingP:string; // the proposition
propStatus:Boolean; // the proposition status
}
here is the Html code for a proposition :
<div class="uk-width-xlarge-1-1 uk-width-medium-1-2">
<div (submit)="addProp1()" class="uk-input-group">
<span class="uk-input-group-addon"><input type="checkbox" data-md-icheck/></span>
<label>Proposition 1</label>
<input [(ngModel)]="proposition1.wordingP" type="text" class="md-input" required class="md-input"/>
</div>
</div>
here is the TypeScript code for adding the proposition:
addProp1() {
this.proposition1 = new PropositionModel();
this.proposition1.propStatus = false;
this.propositionService.addProposition(this.proposition1)
.subscribe(response=> {
console.log(response);
console.log(this.proposition1);
this.proposition1 = new PropositionModel();})
}
And as you can see i made it a false by default for the proposition status and I want to change it once i checked the proposition.
Here is an image how it looks for a better issue understanding.
Any help Please ?
StackBlitz
Template: You can either use the native change event or NgModel directive's ngModelChange.
<input type="checkbox" (change)="onNativeChange($event)"/>
or
<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>
TS:
onNativeChange(e) { // here e is a native event
if(e.target.checked){
// do something here
}
}
onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
if(e){
// do something here
}
}
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
You can use ngModel like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.
Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html
CheckBox: use change event to call the function and pass the event.
<label class="container">
<input type="checkbox" [(ngModel)]="theCheckbox" data-md-icheck
(change)="toggleVisibility($event)"/>
Checkbox is <span *ngIf="marked">checked</span><span
*ngIf="!marked">unchecked</span>
<span class="checkmark"></span>
</label>
<div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>

How can I detect keydown or keypress event in angular.js?

I'm trying to get the value of a mobile number textbox to validate its input value using angular.js. I'm a newbie in using angular.js and not so sure how to implement those events and put some javascript to validate or manipulate the form inputs on my html code.
This is my HTML:
<div>
<label for="mobile_number">Mobile Number</label>
<input type="text" id="mobile_number" placeholder="+639178983214" required
ngcontroller="RegisterDataController" ng-keydown="keydown">
</div>
And my controller:
function RegisterDataController($scope, $element) {
console.log('register data controller');
console.log($element);
$scope.keydown = function(keyEvent) {
console.log('keydown -'+keyEvent);
};
}
I'm not sure how to use the keydown event in angular.js, I also searched how to properly use it. And can i validate my inputs on the directives? Or should I use a controller like what I've done to use the events like keydown or keypress?
Update:
ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.
<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">
<!-- or call a controller/directive method and pass $event as parameter.
With access to $event you can now do stuff like
finding which key was pressed -->
<input ng-keypress="changed($event)">
Read more here:
https://docs.angularjs.org/api/ng/directive/ngKeypress
https://docs.angularjs.org/api/ng/directive/ngKeydown
https://docs.angularjs.org/api/ng/directive/ngKeyup
Earlier solutions:
Solution 1: Use ng-change with ng-model
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController" ng-change="keydown()">
JS:
function RegisterDataController($scope) {
$scope.keydown = function() {
/* validate $scope.mobileNumber here*/
};
}
Solution 2. Use $watch
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController">
JS:
$scope.$watch("mobileNumber", function(newValue, oldValue) {
/* change noticed */
});
You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.
The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):
var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// this next line will convert the string
// function name into an actual function
var functionToCall = scope.$eval(attrs.ngKeydown);
elem.on('keydown', function(e){
// on the keydown event, call my function
// and pass it the keycode of the key
// that was pressed
// ex: if ENTER was pressed, e.which == 13
functionToCall(e.which);
});
}
};
});
The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:
<input type="text" on-keydown="onKeydown">
And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:
$scope.onKeydown = function(keycode){
// do something with the keycode
}
Hopefully that helps either you or someone else who wants to know
You can checkout Angular UI # http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress
(also Enter key, backspace key, alter key ,control key)
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.