数字类型的输入字段未显示默认值(在 angular 中)
Input field of type number is not showing default values (in angular)
我在库存中有以下代码-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,这不是我想要的
如有任何帮助和指导,我们将不胜感激
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;
...
}
如果不想在控制器中初始化变量,可以使用 ng-init 在模板中初始化。
<input type="number" min='0' required [(ngModel)]='updatedStockValue'
ng-init="updatedStockValue=0"/>
我在库存中有以下代码-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,这不是我想要的
如有任何帮助和指导,我们将不胜感激
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;
...
}
如果不想在控制器中初始化变量,可以使用 ng-init 在模板中初始化。
<input type="number" min='0' required [(ngModel)]='updatedStockValue'
ng-init="updatedStockValue=0"/>