代码之家  ›  专栏  ›  技术社区  ›  DAG

角度6自定义输入组件

  •  2
  • DAG  · 技术社区  · 6 年前

    我创造了一个习惯 input 角度为6的组件。此输入组件可以是 text number . 如果是数字,我需要验证 min max

    验证工作正常,但输入值不会在第二次更新。模型更新了tho。

    <input [type]="type" [min]="min" [max]="max" (keyup)="change($event.target.value)" [value]="value">
    

    那是妈妈 事件打开 keypress :

    change(value: any): void {
        if (this.max) {
          if (value > this.max) {
            this.value = this.max;
            this.valueChange.emit(this.value);
            return;
          }
        }
    
        if (this.min) {
          if (value < this.min) {
            this.value = this.min;
            this.valueChange.emit(this.value);
            return;
          }
        }
    
        this.value = value;
        this.valueChange.emit(this.value);
      }
    

    InputComponent

    import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
    
    @Component({
        selector: 'app-custom-input',
        templateUrl: 'input.component.html',
        styleUrls: ['./input.component.scss']
    })
    export class InputComponent implements OnInit {
        @Output() valueChange = new EventEmitter();
    
        @Input() value: any = null;
        @Input() type = 'text';
        @Input() min: number;
        @Input() max: number;
    
        constructor() {}
    
        ngOnInit() {}
    
        change(value: any): void {
          if (this.max) {
            if (value > this.max) {
              this.value = this.max;
              this.valueChange.emit(this.value);
              return;
            }
          }
    
          if (this.min) {
            if (value < this.min) {
              this.value = this.min;
              this.valueChange.emit(this.value);
              return;
            }
          }
    
          this.value = value;
          this.valueChange.emit(this.value);
        }
    }
    

    为什么没有更新输入值?模型正确更新。如果我调试代码,我会看到 this.value

    enter image description here

    上面的图片显示红色圆圈中的值也应该在输入值中。如您所见,模型是正确的,但是输入值没有更新。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Augustin R SOUVIK SAHA    6 年前

    替换 [value] ngModel :

    <input [type]="type" [min]="min" [max]="max" (keyup)="change($event.target.value)" [(ngModel)]="value">
    

    Stackblitz example