【问题标题】:ngForm zero value in custom input number picker自定义输入数字选择器中的 ngForm 零值
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 1970-01-01
      • 2017-09-24
      • 2018-06-06
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2020-03-15
      相关资源
      最近更新 更多