Reputation: 411
I want to detect input
change when I enter input
value, if input
value equal to my condition it will hide
/show
input
element,
this is what I had tried :
ts File
isNoCard = false;
onInputChange(inputValue: number): void {
if (inputValue === 7777) {
this.isNoCard = true;
}
}
html File
<div *ngIf="!isNoCard">
<input (input)="onInputChange($event.target.value)" class="input--2" type="text" >
</div>
<div *ngIf="isNoCard">
<input class="input--1" type="text">
</div>
this is my stackblitz link, but when I had condition, it does not work. Is there any suggestion or guidance to solve this ?
Upvotes: 0
Views: 2600
Reputation: 98
You have used the ===
operator to check the equality, which here will return false
.
This happens because the input value is of type string
and 7777
is a number
.
You can either typecast the value or a simpler way to make this work is to use the ==
operator.
You can use simply the following code:
onInputChange(inputValue: number): void {
if (inputValue == 7777) {
this.isNoCard = true;
}
The ===
operator checks for both the values and type while the ==
operator checks for values only.
Upvotes: 0
Reputation: 483
I think you are comparing inputValue which of type string with number 7777. Even though you have given type of inputValue parameter as number if you try to check the typeof that you would find it to be string.
console.log(typeof inputValue);
A simple solution in this case is to convert string to number by techniques like + operator, parseInt, etc.
If I try to do following it works -
if (+inputValue === 7777) {
this.isNoCard = true;
}
I hope it would be helpful.
Upvotes: 0
Reputation: 17494
Its happening because the value which is being passed from HTML is string
.
Handle it using angular way
<div *ngIf="!isNoCard">
<input [(ngModel)]="data" (ngModelChange)="onInputChange(data)" class="input--2" type="number" >
</div>
Here is sample working stackblitz
Also, take a note that I have made type="number"
because you are expecting the value as number
inside your function.
Upvotes: 1