Angular ngForm自定义输入数字选择器中的零值
我有个问题Angular ngForm自定义输入数字选择器中的零值,angular,input,numbers,picker,Angular,Input,Numbers,Picker,我有个问题 在服务器端PHP上,api返回json,其中某些项具有零值。 我在PHP端使用JSON\u数字\u检查 在角度方面: 我的问题是当match.scoreq1=0=>此值不显示在我的输入=>它保持空白! 当值为零时,它似乎是“未定义的” 注意:match.scoreq1可以为null=>在这种情况下,我希望显示为空 问题在哪里?ngModel?ControlValueAccessor?我想这是因为在writeValue(value)方法中,您检查了if(value), 但如果值
- 在服务器端PHP上,api返回json,其中某些项具有零值。 我在PHP端使用JSON\u数字\u检查
- 在角度方面:
- 我的问题是当match.scoreq1=0=>此值不显示在我的输入=>它保持空白! 当值为零时,它似乎是“未定义的”
问题在哪里?ngModel?ControlValueAccessor?我想这是因为在
writeValue(value)
方法中,您检查了if(value)
,
但如果值为0,则实际计算结果为false,并且永远不会设置组件的值。只需替换if语句,如下所示:
writeValue(value) {
if (value !== null && value !== undefined) {
this.value = value;
}
}
<div class="input-group mb-3 input-md">
<div class="input-group-prepend">
<span class="input-group-text decrease" (click)="decrease();">-</span></div>
<input [name]="name" [(ngModel)]="value" class="form-control counter" type="number" step="1">
<div class="input-group-prepend">
<span class="input-group-text increase" (click)="increase();" style="border-left: 0px;">+</span></div>
</div>
import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-number-picker',
templateUrl: './numberPicker.component.html',
styleUrls: ['./numberPicker.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NumberPickerComponent),
multi: true
}
]
})
export class NumberPickerComponent implements ControlValueAccessor {
@Input()
name: string;
@Input() val: number;
// Both onChange and onTouched are functions
onChange: any = () => { };
onTouched: any = () => { };
get value() {
return this.val;
}
set value(val) {
this.val = val;
this.onChange(val);
this.onTouched();
}
// We implement this method to keep a reference to the onChange
// callback function passed by the forms API
registerOnChange(fn) {
this.onChange = fn;
}
// We implement this method to keep a reference to the onTouched
// callback function passed by the forms API
registerOnTouched(fn) {
this.onTouched = fn;
}
// This is a basic setter that the forms API is going to use
writeValue(value) {
if (value) {
this.value = value;
}
}
decrease() {
if (this.value === 0 || this.value === null) {
this.value = null;
} else {
this.value--;
}
}
increase() {
if (isNaN(this.value) || this.value === null) {
this.value = 0;
} else {
this.value++;
}
}
}
writeValue(value) {
if (value !== null && value !== undefined) {
this.value = value;
}
}