change style using ngModelChange - html

I was wondering if it was possible to style an element using ngModelChange. I tried the following but that doesn't work
<input class="input" [(ngModel)]="counter" (ngModelChange)="$event > 2 ? [style.border-color]='#ff4d4d' : [style.border-color]='#dbdbdb'" type="number">
I know that I could do something like
<input class="input" [(ngModel)]="counter" (ngModelChange)="$event > 2 ? error=true : error=false" type="number" [style.border-color]="error ? '#ff4d4d' : '#dbdbdb'">
But I want to remove if possible the 'error' attribute and assign directly the style to the input depending of the condition

Instead of handling ngModelChange, you could use normal style binding with the condition on counter, which has the same value as the $event parameter of ngModelChange:
<input [(ngModel)]="counter" [style.border-color]="counter > 2 ? '#ff4d4d' : '#dbdbdb'" class="input" type="number">
See this stackblitz for a demo.

I don't think that will be possible as we can't do property binding [style] inside an event binding (ngModelChange) as one is happening at the view and another at Model.

You can clean your code by adding function based approach.
HTML
<input class="input" [(ngModel)]="counter" (ngModelChange)="changeColor($event)" type="number" [style.border-color]="color" type="number">
.TS
color="dbdbdb";
changeColor(event) {
if(event > 2){
this.color = "#ff4d4d";
}else{
this.color = "#dbdbdb";
}
}

Related

Checked property not working in my Angular html template

When I implemented my html template, checked property of checkbox is not properly working.
My html file contains code like the following,
<div *ngIf="userPermissionObj" >
<label for="pm">Permissions:</label>
<div *ngFor="let pt of permissionType">
<label>
<input type="checkbox"
[value]="pt.id"
ng-checked="${userPermissionObj.sPermissionType} == ${pt.name} ? true : false" />
{{pt.name}}
</label>
</div>
How can I find out where I implemented in wrong way?
In new Angular ng-checked does not exists. To acheive the same, use [checked]:
<input type="checkbox" [checked]="'Your_condition_here' ? true : false" (change)="someMethod()"/>
Use [checked] instead of ng-checked (It is angularJS directive, not angular.io),
See example below,
<input type="checkbox"
[value]="pt.id"
[checked]="${userPermissionObj.sPermissionType} == ${pt.name} ? true : false" >

Add a checked attribute to a dynamic radio button

I'm building a *ngFor dynamic radio button. I need to add some kind of attribute that can be used to determine if the button is active or not. This is not for the purpose of functionality, the selection builds the property on my reactive form fine. The purpose is to satisfy testing.
<label *ngFor="let order of orders">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" />
{{order.name}}
</label>
I've tried adding a checked attribute but this just adds the attribute to all radios. I thought angular provided a ngChecked property, but I think that was for AngularJS.
Any solution to determine/show that the selected radio is active would be a solution.
https://stackblitz.com/edit/angular-t2gd4g
simply by get the value of the form control orders you will be applied to know the selected one or in case of apply a spesifect design you can add a checked class for the selected one
<label *ngFor="let order of orders"
[ngClass]="{'checked':form.get('orders').value == order.id}">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" />
{{order.name}}
</label>
another way to get the selected order by create a property
get selectedOrder() {
const selected =this.form.get('orders').value;
if (selected) {
return this.orders.find(o => o.id == selected )
} else {
return null
}
}
demo 🚀
In your .ts file declare changeHandler() function like this :
changeHandler(index){
console.log(`radio-button ${index+1} is active`);
}
In your .html file, in your *ngFor declare index which can be used to find the current state of checkbox. So the following demo shows which checkbox is active :
<label *ngFor="let order of orders; let i = index;">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" (ngModelChange)="changeHandler(i)"/>
{{order.name}}
</label>
Demo : enter link description here
Note : see console to see active button

To allow only one numeric value in text box based on regular expression in AngularJs

I'm using ng-pattern :
<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^[4]*$/" required only-digits>
Please let me know what to do that it does not accept any other numbers except 4. I am using directive for digits that is only-digits.
EDIT: SORRY WRONG ANGULAR VERSION - but if you can transform this to angularjs it will be work!
You can use (input) event in you HTML input element
<input type="number" (input)="check($event)">
Than in your ts you cehck value of input
check(event) {
console.log(event);
if (+event.data !== 4) {
event.target.value = '';
}
}
The pattern which you are mentioned is not a valid regex pattern. Instead of that try to use this /^([4]){1}?$/ Hope you will get it.
<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^([4]){1}?$/" required only-digits>
Try to use below restrict pattern :
<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="^[4]{1}?$" required only-digits>
And below validation message :
<div ng-messages="myForm.price_field.$error">
<span ng-message="pattern">Not a valid number!</span>
</div>

Hide 'Zero' value in input using typescript and Angular 2

<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel">
Here I have to hide zero amount while user entering the values.
If he enters all zero's then only we have to hide not in cases like 20,30,100 etc...
I'm using Angular 2.
<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel"
(keyup)="hideZero()>
Added This keyUp event in Html and in .ts added below code
hideZero(){
if(this.userBalance.transactionAmount === '0' ){
this.userBalance.transactionAmount = '';
}
}
Working Absolutely fine
/* In your ts */
validateNumber(value: String) {
userBalance.transactionAmount = value && value.replace(/(?:0*)(\d*)/g, (_,value1) => {
return value1;
})
}
<input (input)="validateNumber($event)">
Try using (ngModelChange) event which will trigger when user types values. By using regex, you can remove the last zero value and update the DOM. Hope this helps.
Angular 0 value don't display
<span *ngIf="!pro.model === '0'">{{ pro.model }}</span>
Like this,
When model value is zero that time don't display model value.
If model value is not zero that time show model value in your html pages.

How do you automatically set text box to Uppercase?

I am using the following style attribute to set the user input to uppercase so that when the user starts typing in the text box for example railway, then it should be altered to capital letters like RAILWAY without the user having to press the Caps-lock button.
This is the code I am using for the input:
<input type = "text" class = "normal" name = "Name" size = "20" maxlength = "20"> <img src="../images/tickmark.gif" border="0" style='text-transform:uppercase'/>
But I am not getting the desired output by using this attribute.
You've put the style attribute on the <img> tag, instead of the <input>.
It is also not a good idea to have the spaces between the attribute name and the value...
<input type="text" class="normal"
name="Name" size="20" maxlength="20"
style="text-transform:uppercase" />
<img src="../images/tickmark.gif" border="0" />
Please note this transformation is purely visual, and does not change the text that is sent in POST.
NOTE: If you want to set the actual input value to uppercase and ensure that the text submitted by the form is in uppercase, you can use the following code:
<input oninput="this.value = this.value.toUpperCase()" />
I think the most robust solution that will insure that it is posted in uppercase is to use the oninput method inline like:
<input oninput="this.value = this.value.toUpperCase()" />
EDIT
Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that
<input oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);" />
The answers with the text-transformation:uppercase styling will not send uppercased data to the server on submit - what you might expect. You can do something like this instead:
For your input HTML use onkeydown:
<input name="yourInput" onkeydown="upperCaseF(this)"/>
In your JavaScript:
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
With upperCaseF() function on every key press down, the value of the input is going to turn into its uppercase form.
I also added a 1ms delay so that the function code block triggers after the keydown event occured.
UPDATE
Per recommendation from Dinei, you can use oninput event instead of onkeydown and get rid of setTimeout.
For your input HTML use oninput:
<input name="yourInput" oninput="this.value = this.value.toUpperCase()"/>
The problem with the first answer is that the placeholder will be uppercase too. In case you want ONLY the input to be uppercase, use the following solution.
In order to select only non-empty input element, put required attribute on the element:
<input type="text" id="name-input" placeholder="Enter symbol" required="required" />
Now, in order to select it, use the :valid pseudo-element:
#name-input:valid { text-transform: uppercase; }
This way you will uppercase only entered characters.
try
<input type="text" class="normal"
style="text-transform:uppercase"
name="Name" size="20" maxlength="20">
<img src="../images/tickmark.gif" border="0"/>
Instead of image put style tag on input because you are writing on input not on image
Set following style to set all textbox to uppercase:
input { text-transform: uppercase; }
Using CSS text-transform: uppercase does not change the actual input but only changes its look.
If you send the input data to a server it is still going to lowercase or however you entered it. To actually transform the input value you need to add javascript code as below:
document.querySelector("input").addEventListener("input", function(event) {
event.target.value = event.target.value.toLocaleUpperCase()
})
<input>
Here I am using toLocaleUpperCase() to convert input value to uppercase.
It works fine until you need to edit what you had entered, e.g. if you had entered ABCXYZ and now you try to change it to ABCLMNXYZ, it will become ABCLXYZMN because after every input the cursor jumps to the end.
To overcome this jumping of the cursor, we have to make following changes in our function:
document.querySelector("input").addEventListener("input", function(event) {
var input = event.target;
var start = input.selectionStart;
var end = input.selectionEnd;
input.value = input.value.toLocaleUpperCase();
input.setSelectionRange(start, end);
})
<input>
Now everything works as expected, but if you have slow PC you may see text jumping from lowercase to uppercase as you type. If this annoys you, this is the time to use CSS, apply input: {text-transform: uppercase;} to CSS file and everything will be fine.
The issue with CSS Styling is that it's not changing the data, and if you don't want to have a JS function then try...
<input onkeyup="this.value = this.value.toUpperCase()" />
on it's own you'll see the field capitalise on keyup, so it might be desirable to combine this with the style='text-transform:uppercase' others have suggested.
Various answers here have various problems, for what I was trying to achieve:
Just using text-transform changes the appearance but not the data.
Using oninput or onkeydown changes the cursor position, so you can't, for instance, click in the middle of your existing input and edit it.
Saving the position works, but just seemed a bit kludgey.
It felt cleaner to me to just break the problem up into two parts: upper-casing what I'm typing while I type (text-transform), and upper-casing the submitted data (run toUpperCase onchange):
<input id = "thing" onchange="this.value = this.value.toUpperCase(); pr()" style=text-transform:uppercase /><p>
<b><span id="result"></span></b>
<script>function pr() {document.getElementById("result").innerHTML = document.getElementById("thing").value}</script>
Type something in that, hit return or click out of the input, then click in the middle of your previous entry, add some lc text, hit return...
IN HTML input tag just style it like follows
<input type="text" name="clientName" style="text-transform:uppercase" required>
in backed php/laravel use:
$name = strtoupper($clientName);
This will both show the input in uppercase and send the input data through post in uppercase.
HTML
<input type="text" id="someInput">
JavaScript
var someInput = document.querySelector('#someInput');
someInput.addEventListener('input', function () {
someInput.value = someInput.value.toUpperCase();
});
As nobody suggested it:
If you want to use the CSS solution with lowercase placeholders, you just have to style the placeholders separately. Split the 2 placeholder styles for IE compatibility.
input {
text-transform: uppercase;
}
input:-ms-input-placeholder {
text-transform: none;
}
input::placeholder {
text-transform: none;
}
The below input has lowercase characters, but all typed characters are CSS-uppercased :<br/>
<input type="text" placeholder="ex : ABC" />
<input style="text-transform:uppercase" type = "text" class = "normal" name = "Name" size = "20" maxlength = "20"> <img src="../images/tickmark.gif" border="0"/>
I went with the style text-transform:uppercase thing from poster. Then I just did the uppercase thing in php as well. Some people working too hard with that javascript.
You were close with the style being in the wrong place. You were trying to uppercase an image instead of the input.
$name = strtoupper($_POST['Name']);
I don't know why I wanted to throw in some extra stuff if it's a php page. This is something I like to do make it smoother for the person filling out the form.
<input style="text-transform:uppercase" type = "text" class = "normal" name = "Name" size = "20" maxlength = "20" value="<?php echo $name; ?>"> <img src="../images/tickmark.gif" border="0"/>
That's assuming you're using PHP as the backend and posting to the same page you are on. This will keep the user from having to fill out that part of the form again. Less annoying for the person filling out the form.
Try below solution, This will also take care when a user enters only blank space in the input field at the first index.
document.getElementById('capitalizeInput').addEventListener("keyup", () => {
var inputValue = document.getElementById('capitalizeInput')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);
}
document.getElementById('capitalizeInput')['value'] = inputValue;
});
<input type="text" id="capitalizeInput" autocomplete="off" />
Just use this oninput in your input field:
<div class="form-group col-2">
<label>PINCODE</label>
<input type="number" name="pincode" id="pincode" class="form-control" minlength="6" maxlength="6" placeholder="Enter Pincode" oninput="this.value = this.value.toUpperCase()" autocomplete="off">
</div>
Just add in your input(style="text-transform:uppercase")
<input type="text" class="normal" style="text-transform:uppercase" name="Name" size="20" maxlength="20">
<script type="text/javascript">
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
</script>
<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">