简体   繁体   English

打字稿 .length 返回未定义

[英]Typescript .length return undefined

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'.我的问题: control.value.length总是返回“未定义”。

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编辑:精度:我的 control.value 不为 null 或为空,我用值 59000 进行测试

This code :此代码:

console.log(control.value + ' - ' + control.value.length);

log this : 59000 - undefined记录这个: 59000 - 未定义

EDIT 2 : Thank's you, it's solved.编辑2:谢谢你,它已经解决了。 The problem was my control.value was a number and not a string .问题是我的 control.value 是一个数字而不是一个字符串

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.在这种情况下val.length返回undefined因为数字没有length属性。

See this plunkr for more details: https://plnkr.co/edit/5yp5ms9XY5Z3TEE2qYIh?p=preview .有关更多详细信息,请参阅此 plunkr: https ://plnkr.co/edit/5yp5ms9XY5Z3TEE2qYIh?p = preview。

Try Like these试试像这些

String(control.value).length != 5

OR或者

control.value.toString().length != 5

In Typescript:在打字稿中:

     let a="hello";
     let length=a.toString().length;
     console.log(length);

Output: 5输出: 5

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 :有时在 Angular 上有这个错误,我认为从 5.0.0 版本开始,即使变量不是数字,我也必须将其转换为数字以使用“.length”属性,如下所示:

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)它可能会起作用,只需在 var.length 之前添加符号“+”,例如: +(var.length)

I had the same issue before, in my case my object was set with a string with lowercase "s" therefore an Angular primitive.我之前遇到过同样的问题,在我的情况下,我的对象设置了一个带有小写“s”的字符串,因此是一个 Angular 原语。 You need to add toString() before the length: control.value.toString().length.您需要在长度之前添加 toString():control.value.toString().length。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM