【发布时间】:2018-09-02 05:47:27
【问题描述】:
我正在构建一个 Angular 5 应用程序来跟踪利润。 我的应用程序有多个输入字段。
如果我卖巧克力,我会按 + 按钮来增加数量。
如果我卖 Wine,我会按 Wine 输入旁边的 + 按钮来增加计数。
现在我使用了 incrementchoc() 函数来增加巧克力的数量 和 incrementwine() 函数来增加酒的数量。
下面是我的 HTML:
<div >
<label>Chocolate:</label><br>
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-danger btn-number" (click)= "decrementchoc()" data-type="minus" data-field="quant[2]">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" name="quant[2]" [(ngModel)]="info.choco" (keyup)="choc(info.choco)" class="form-control input-number" value="{{info.choco}}" >
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-number" (click)= "incrementchoc()" data-type="plus" data-field="quant[2]">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div></div>
<div >
<label>Wine:</label><br>
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-danger btn-number" (click)= "decrementwine()" data-type="minus" data-field="quant[3]">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" name="quant[3]" [(ngModel)]="info.wine" (keyup)="wine(info.wine)" class="form-control input-number" value="{{info.wine}}" >
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-number" (click)= "incrementwine()" data-type="plus" data-field="quant[3]">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div></div>
我也附上一张图片。 This is how my HTML looks like with the - and + buttons
下面是我的 Component.ts 文件的代码
incrementchoc(){
this.info.choco= ++this.info.choco;
}
decrementchoc(){
this.info.choco= --this.info.choco;
}
incrementwine(){
this.info.wine= ++this.info.wine;
}
decrementwine(){
this.info.wine= --this.info.wine;
}
您可以从上面的代码中清楚地看到,如果我有 n 个输入字段,那么我将不得不编写 n 个递增和递减函数。我认为这会使应用程序变得非常繁重。
请建议我一种更好的方法,通过使用单个函数通过检测输入的 ngModel 并仅递增/递减该值而不是编写 n 个函数来递增递减值。
【问题讨论】:
标签: angular increment decrement