【发布时间】:2020-02-21 16:16:33
【问题描述】:
我有问题
在服务器端 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++;
}
}
}
- 我的问题是当 match.scoreEq1 = 0 => 这个值没有显示在我的输入中 => 它保持空白! 当值为零时,它似乎“未定义”。
注意:match.scoreEq1 可以为 null => 在这种情况下我想显示空白
问题出在哪里?模型?控制值访问器?
【问题讨论】:
标签: angular input numbers picker