我有问题
在服务器端PHP上,api返回json,其中某些项目的值为零。我在PHP端使用JSON_NUMERIC_CHECK。
在有角度的一面:
<app-number-picker name="scoreEq1" [(ngModel)]="match.scoreEq1" #score="ngModel"></app-number-picker>
然后,我自定义了号码选择器组件:
<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>
我的代码的灵感来自blog.thoughtram.io在组件ts中:
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++;
}
}
}
NB:match.scoreEq1可以为null =>在这种情况下,我想显示为空白
问题出在哪里? ngModel? ControlValueAccessor?
我猜是因为在writeValue(value)
方法中您选中了if(value)
,但是,如果您的值为0,则该值实际上为false,并且永远不会设置组件的值。只需替换if语句,如下所示:
writeValue(value) {
if (value !== null && value !== undefined) {
this.value = value;
}
}