我正在关注此plunker。这里的递增和递减按钮可用于设置任何数字。我可以多次点击减号按钮来设置负数。我怎么能把它限制在几个数字?例如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++;
}
}
答案 0 :(得分:2)
decrement() {
if(this.counter > 0)
this.counter--;
}
increment() {
if(this.counter < 5)
this.counter++;
}
答案 1 :(得分:0)
只需使用简单的if
条件即可。 Demo
decrement() {
if(this.counter > 0)
this.counter--;
}
increment() {
if(this.counter <5)
this.counter++;
}
答案 2 :(得分:0)
您可以通过组件的打字稿或通过组件模板
来完成此操作<强>打字稿强>
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>