Reputation: 281
I'm trying to create a component input with the type number where you can setup a max and a min with Angular
Here is my code : This is the HTML code which called the component :
<app-input-number [(value)]="inputMinMaxValueNumber" [min]="min" [max]="max"></app-input-number>
This is the HTML code for the component :
<input class="gh-input" type="number" [max]="max" [min]="min" [name]="name"
[readonly]="readonly" [disabled]="disabled" [ngClass]="disabled ? 'disabled' : ''" [value]="value" />
And the typescript for the component :
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-input-number',
templateUrl: './input-number.component.html',
styleUrls: ['./input-number.component.scss']
})
export class InputNumberComponent implements OnInit {
@Input() name: String;
@Input() readonly: Boolean;
@Input() disabled: Boolean;
@Input() max: number;
@Input() min: number;
currentValue: number;
@Output()
valueChange = new EventEmitter<number>();
@Input()
get value() {
return this.currentValue;
}
set value(val) {
if (val > this.max) {
this.currentValue = this.max;
} else if (val < this.min) {
this.currentValue = this.min;
} else {
this.currentValue = val;
}
this.valueChange.emit(this.currentValue);
}
constructor(private translateService: TranslateService) { }
ngOnInit() {
}
}
The problem is that when i'm entering a value manually by entering a value higher then the max, it'll work the first time but then it won't limit the value anymore (it works for the min tho)
Any help would be welcomed.
Upvotes: 1
Views: 475
Reputation: 359
It won't work because you cannot two-way bind with value
property to input
element. Use ngModel
instead.
BUT anyway, using ngModel
, or in general two-way binding, is your worst option. Use FormGroups with custom validators instead.
Upvotes: 1