Check the following Stackblitz Demo
Html:
<input type="text" [maxLength]="maxLength" [ngModel]="value" (ngModelChange)='up($event)'/>
app.component.ts:
import { Component, Injectable } from '@angular/core';
@Injectable()
export class MyService {
MAXLENGTH = 2;
getMaxLength() {
return this.MAXLENGTH;
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 4';
maxLength: number;
value = 0;
constructor(private myService: MyService) {
this.maxLength = myService.getMaxLength();
}
up(newValue) {
console.log(newValue);
if (newValue < 0) {
this.value = 0;
} else if (newValue > 50) {
this.value = 50;
} else {
this.value = newValue;
}
}
}
Explanation:
MAXLENGTH = 2;
getMaxLength() {
return this.MAXLENGTH;
}
Used to limit input length to x
where as in example x=2.
Core to limit value:
up(newValue) {
if (newValue < 0) {
this.value = 0;
} else if (newValue > 50) {
this.value = 50;
} else {
this.value = newValue;
}
}
Checked whether value was less than 0 or more than 50 and if not set them to min/max value.