javascript - TypeScript Angular - 将字符串添加到数字属性会导致值为零 (0)

标签 javascript angular typescript

我正在使用 Angular 和 Typescript,我想知道如果我将一个字符串值(例如“hahah”)添加到一个应该只接受数字的字段并且它绑定(bind)到类型数字的属性也不会触发或触发任何错误,该字段的值将为零!我的意思是这对我来说很好,结果为零比结果为某个奇怪的值更好,但我很好奇这是怎么回事?

这是我的 typescript 类的样子:

export class Article {

  public id: string;
  public price: number;
  public price2: number;

 }

这是我的模板 .html 文件:

<div class="form-group">
  <label class="control-label dash-control-label col-sm-3" for="">Price:</label>
  <div class="col-sm-3">
    <input type="text" class="form-control dash-form-control" id="" placeholder="" name="price" [(ngModel)]="article.price">
  </div>

  <label class="control-label dash-control-label col-sm-3" for="">Price 2:</label>
  <div class="col-sm-3">
    <input type="text" class="form-control dash-form-control" id="" placeholder="" name="price2" [(ngModel)]="article.price2">
  </div>
</div>

正如你所看到的,输入绑定(bind)到 [(ngModel)]="article.price"[(ngModel)]="article.price2" 应用程序运行时它们看起来像这样:

enter image description here

但如果我输入如下内容,一切都很好:

enter image description here

当我发帖时,我的数据库中存储的值是:零 (0)!

怎么会?

为什么我尝试将字符串添加到数字或其他内容时没有出现错误?

谢谢

最佳答案

是啊!

Typescript changing the value depends by the property type without throwing error.

喜欢

add(a:number , bnumber )
  {
    console.log(a+b); 
  }

add("1",2);// result is 3 

所以如果你传递字符串 add("aa"+"aa"); 它返回 0。因为函数参数 (number n,number n2) 是类型.所以它正在转换一个数字(如果它不是一个数字那么它假设为 0)


建议:

the better way is you can use type="number" instead of type="text" in your input element to avoiding to type any string value in the input box

<div class="form-group">
  <label class="control-label dash-control-label col-sm-3" for="">Price:</label>
  <div class="col-sm-3">
    <input type="number" class="form-control dash-form-control" id="" placeholder="" name="price" [(ngModel)]="article.price">
  </div>

  <label class="control-label dash-control-label col-sm-3" for="">Price 2:</label>
  <div class="col-sm-3">
    <input type="number" class="form-control dash-form-control" id="" placeholder="" name="price2" [(ngModel)]="article.price2">
  </div>
</div>

关于javascript - TypeScript Angular - 将字符串添加到数字属性会导致值为零 (0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50567627/

相关文章:

javascript - 倒数计时器在页面刷新时重置

c# - ASP.NET MVC (Razor) 与 Angular 5

angular - 模型驱动/ react 形式 : Auto mapping from Model to FormGroup ?

node.js - Volta 与yarn run 构建系统找不到指定的路径

typescript - 假运算符重载

javascript - number 只能输入数字

javascript - 除法和四舍五入

javascript - jQuery 验证在按键时不触发

angular - NGXS 错误 : Can't resolve all parameters for TranslationEditorState: (? )

javascript - 创建秒表时出错