如何解决Angular中生成的文本字段的问题

时间:2018-01-06 16:19:57

标签: javascript angular

我在我的项目中使用Angular,并且我有这个JSON对象:

items={"departure":"New York","arrival":"California","stations":[{"station":"toto"},{"station":"titi"},{"station":"tata"}]}

我尝试在用户界面中填充此JSON对象,如this picture

这是我的代码:

<div class="panel-body panelcolor">

<div *ngIf="items?.departure">
<span>{{items.departure}}</span> --> 
<span *ngIf="items.stations.length > 0">
    {{items.stations[0].station}}
</span>
<span *ngIf="items.stations.length === 0">
    {{items.arrival}}
</span>

<div class="input-group spinner">
    <input type="text" formControlName="price" class="form-control">
    <div class="input-group-btn-vertical">
        <button (click)="spinnerPriceUp()" class="btn btn-default" 
 type="button"><i class="fa fa-caret-up"></i></button>
        <button (click)="spinnerPriceDown()" class="btn btn-default" 
  type="button"><i class="fa fa-caret-down"></i></button>
    </div>
</div>
</div>    

<div *ngFor="let item of items.stations; let i=index, let last = last">

<div *ngIf="!last">
    <span>{{item.station}}</span> --> <span *ngIf="items.stations[i+1]">{{items.stations[i+1].station}}</span>
    <div class="input-group spinner">
        <input type="text" formControlName="price" class="form-control">
        <div class="input-group-btn-vertical">
            <button (click)="spinnerPriceUp()" class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
            <button (click)="spinnerPriceDown()" class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
        </div>
    </div>
   </div>

</div>

<div *ngIf="items?.arrival && items?.stations.length > 0">
<span>{{items.stations[items.stations.length-1].station}}</span> --> <span>{{items.arrival}}</span>
<div class="input-group spinner">
    <input type="text" formControlName="price" class="form-control">
    <div class="input-group-btn-vertical">
        <button (click)="spinnerPriceUp()" class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
        <button (click)="spinnerPriceDown()" class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
    </div>
</div>

spinnerPriceUp()函数代码:

spinnerPriceUp(){
let price=parseInt(`${this.myForm.value.price}`)+1;
this.myForm.controls['price'].setValue(price)
 }

spinnerPriceDown()函数代码:

 spinnerPriceDown(){
   if(parseInt(`${this.myForm.value.price}`) > 0){
    let price=parseInt(`${this.myForm.value.price}`)-1;
    this.myForm.controls['price'].setValue(price)
 }
}

我的问题是当我尝试单击(向上或向下)微调器以更改文本框的值时,所有文本框都会更改其值。任何人都可以帮我解决这个问题吗?我试图使用表单组来解决这个问题,但我无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

非常接近,但是唉,我确定我们之前已经为这个伎俩而堕落......

所有输入控件都命名为&#34; price&#34;,您的函数正在修改formControl,其名称为price。

您将通过索引更新formGroup的控件集合中的控件,或者通过它的关联工作站访问控件。