自定义输入数字选择器中的 ngForm 零值

ngForm zero value in custom input number picker

我有问题

<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 可以为空 => 我想在那种情况下显示空白

问题出在哪里?纳格模型?控件值访问器 ?

我想这是因为在你的 writeValue(value) 方法中你检查了 if(value), 但如果您的值为 0,则这实际上评估为 false,并且永远不会设置您的组件的值。只需将 if 语句替换如下:

writeValue(value) {
   if (value !== null && value !== undefined) {
     this.value = value;
   }
}