[英]how to limit values in counter in angular 2
我正在追随这个笨蛋 。 此处的增减按钮可用于设置任何数字。 我可以多次单击减号按钮来设置负数。 如何将其限制为仅几个数字? 例如仅0到5。 我的意思是数字不应低于0和高于5。
export class CustomCounterComponent {
counterValue = 0;
@Output() counterChange = new EventEmitter();
@Input()
get counter() {
return this.counterValue;
}
set counter(val) {
this.counterValue = val;
this.counterChange.emit(this.counterValue);
}
decrement() {
this.counter--;
}
increment() {
this.counter++;
}
}
decrement() {
if(this.counter > 0)
this.counter--;
}
increment() {
if(this.counter < 5)
this.counter++;
}
只需使用简单的if
条件。 演示版
decrement() {
if(this.counter > 0)
this.counter--;
}
increment() {
if(this.counter <5)
this.counter++;
}
您可以通过组件的打字稿或通过组件模板来执行此操作
打字稿
increment(){
if(this.counter < 5){
this.counter++;
}
}
decrement(){
if(this.counter > 0){
this.counter--;
}
}
零件
检查分叉的plnkr
<button [disabled]="counter == 0" (click)="decrement()">-</button>
<span>{{counter}}</span>
<button [disabled]="counter == 5" (click)="increment()">+</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.