Reputation: 9391
This issue makes me crazy ...
I have this code :
if (control.value==null||control.value == "" || control.value == " " || control.value.length != 5) {
// do something
}
My problem : control.value.length
always returns 'undefined'.
I try to use a string variable like this but the result is the same.
var curVal: string = control.value;
if (curVal==null||curVal== "" || curVal == " " || curVal != 5) {
// do something
}
Where am I wrong ?
Edit: Precision : my control.value is not null or empty, I test with the value 59000
This code :
console.log(control.value + ' - ' + control.value.length);
log this : 59000 - undefined
EDIT 2 : Thank's you, it's solved. The problem was my control.value was a number and not a string.
Upvotes: 12
Views: 43020
Reputation: 11
let a="hello";
let length=a.toString().length;
console.log(length);
Output: 5
Upvotes: 1
Reputation: 131
Try Like these
String(control.value).length != 5
OR
control.value.toString().length != 5
Upvotes: 4
Reputation: 733
Sometimes there is this bug on Angular, since version 5.0.0 I think, even when the variable is not a number, I've to convert it to a number to use the '.length' property like below :
if (control.value==null||control.value == "" || control.value == " " || +(control.value.length) != 5) {
// do something
It may works, just by adding the sign '+' before your var.length like: +(var.length)
Upvotes: 0
Reputation: 202176
I think that the type of your input isn't string but number.
@Component({
selector: 'my-app',
template: `
<div>
<input type="number" [ngFormControl]="ctrl">
</div>
`
})
export class AppComponent {
constructor() {
this.ctrl = new Control();
this.ctrl.valueChanges.subscribe((val) => {
console.log(val.length);
});
}
}
In this case val.length
returns undefined
since numbers don't have a length
attribute.
See this plunkr for more details: https://plnkr.co/edit/5yp5ms9XY5Z3TEE2qYIh?p=preview.
Upvotes: 7