错误TypeError:无法读取null的属性“0”

时间:2018-01-19 19:25:00

标签: javascript jquery angular

我正在尝试使用Angular通过ngFor动态生成一些文本字段,但它会出错。

以下是代码:

<div *ngFor="let item of items.stations; let i=index, let last = last" style="margin-bottom: 2px;">

<div class="row">
    <div *ngIf="!last">
        <div class="col-sm-4" >
            <div  style="">
                <div class="inner-addonx left-addon header-search" style="float:left;margin-right: 4px;">
                    <i class="glyphicon  markerx" style="border: 5px solid #FED141"></i>
                  </div>
              <span>{{item.station}}</span>
            </div> 
        </div>
        <div class="col-sm-1"><img style="    width: 32px;    height: 22px;" src="../assets/img/arrow.svg" ></div>
        <div class="col-sm-4" >
            <span *ngIf="items.stations[i+1]">{{items.stations[i+1].station}}</span>
        </div>
        <div class="col-sm-3" >
            <div class="input-group ">
              <input hidden  [attr.id]="'stationne' + i" #statione value='{{item.station}}  -  {{items.stations[i+1].station}}' />
                <div class="input-group spinner">
                  <input type="text" (blur)="onSearchChange(price.value,'stationne' + i)" #price id="'lastPrice'+i" value="12"  class="form-control "  />
                  <span class="input-group-addon">Dhs</span>
                  <div class="input-group-btn-vertical">
                      <button (click)="spinnerPriceUp(price.value,'lastPrice',i);onSearchChange(price.value,'stationne' + i)" class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
                      <button (click)="spinnerPriceDown(price.value,'lastPrice',i);onSearchChange(price.value,'stationne' + i)" class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
                  </div>
                </div>
            </div>
        </div>
    </div>
</div>

她是JS代码:

 spinnerPriceUp(textFieldId, id,to){

let price=parseInt(textFieldId)+1;
alert(price);
 //this.myForm.controls['stepfinal'].setValue(price);
(<HTMLInputElement> document.getElementById(id))[to].value = price;
 }

当我尝试点击微调器来提升数字(执行上面的功能)时,它给了我这个错误:

  

错误类型错误:无法读取null

的属性“0”

1 个答案:

答案 0 :(得分:0)

我可能会遗漏一些东西,但似乎你只想增加和放大减少输入。为此,您无需直接访问该文档。您正在使用price模板var,因此您可以执行

// html
<input #price value="12">
<button (click)="spinnerPriceUp(price)"></button>
<button (click)="spinnerPriceDown(price)"></button>

// ts                    
spinnerPriceUp(price){
    price.value++;
}
spinnerPriceDown(price){
    price.value--;
}

此外,angular建议您避免直接访问窗口/文档对象,以防您的代码在没有该对象的环境中运行。

以下是演示stack blitz