[英]Angular 6 custom Input component
我已經在Angular 6中創建了一個自定義input
組件。該輸入組件可以是text
或number
類型的。 如果是數字,則需要驗證min
和max
。
驗證有效,但是輸入的值不會第二次更新。 模型將更新。
該組件如下所示:
<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
是期望的值,但在DOM中不是。
上圖顯示紅色圓圈中的值也應在輸入值中。 如您所見,模型是正確的,但是輸入值未更新。
將[value]
替換為ngModel
:
<input [type]="type" [min]="min" [max]="max" (keyup)="change($event.target.value)" [(ngModel)]="value">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.