【问题标题】:Input field of type number is not showing default values (in angular)类型编号的输入字段未显示默认值(角度)
【发布时间】:2020-07-24 13:32:10
【问题描述】:

我在 stock-status.component.ts 文件中有以下代码

@Component({
  selector: 'app-stock-status',
  template:`
  <input type="number" value='0' min='0' required [(ngModel)]='updatedStockValue'/>
  <button class="btn btn-primary" [style.background]='color' (click)='stockValueChanged()'>Change Stock Value</button>
    
  `,
  styleUrls: ['./stock-status.component.css']
})

正如您在图片中看到的那样,它没有将默认值显示为 0 enter image description here

每当我在没有数据初始化的情况下单击按钮时,它都会显示 NaN,这不是我想要的

任何形式的帮助和指导将不胜感激

【问题讨论】:

    标签: html angular input angular-template


    【解决方案1】:

    ngModel 绑定在这里可能具有优先权。您可以忽略value 属性并在其定义中设置updatedStockValue

    试试下面的

    @Component({
      selector: 'app-stock-status',
      template:`
      <input type="number" min="0" required [(ngModel)]="updatedStockValue"/>
      <button class="btn btn-primary" [style.background]="color" (click)="stockValueChanged()">Change Stock Value</button>
        
      `,
      styleUrls: ['./stock-status.component.css']
    })
    export class AppComponent {
      updatedStockValue: number = 0;
      ...
    }
    

    【讨论】:

      【解决方案2】:

      如果您不想在控制器中进行初始化,可以使用 ng-init 初始化模板中的变量。

        <input type="number" min='0' required [(ngModel)]='updatedStockValue'
        ng-init="updatedStockValue=0"/>
      

      【讨论】:

      • 感谢您的回答,但它似乎不起作用,并且与我的代码具有相同的错误 @Michael 的回答效果很好
      猜你喜欢
      • 2014-06-12
      • 2018-03-26
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2021-04-27
      • 2019-05-18
      • 1970-01-01
      相关资源
      最近更新 更多