【问题标题】:Binding Two-ways : array of numbers within angular application绑定两种方式:角度应用程序中的数字数组
【发布时间】:2018-07-22 01:06:13
【问题描述】:

我需要以两种方式将一个数字数组与一组输入数字绑定:

Ligne.Component.ts

export class LigneComponent implements OnInit {

  @Input() cells: Array<number>;

  constructor(private lgservice: LigneserviceService ) {
    this.lgservice.init(4032,10);
    this.cells = this.lgservice.cells;
    }

  ngOnInit() {
  }
  onSearchChange() {

      for (let cell of this.cells) {
      {
        console.log(cell);
      }
  }
}

Ligne.Component.html

<div *ngFor="let cell of cells">
  <input value="{{cell}}" type="number" [min]="0" [max] ="9" maxlength="1" class="row" (input)="onSearchChange()" >
</div>

似乎绑定以单一方式工作,即:我得到默认值(等于 0)。但是当我更改单元格的值时,我总是得到 0 作为所有单元格的值!

所以我需要知道如何解决这个问题?

谢谢,

【问题讨论】:

    标签: javascript html angular typescript binding


    【解决方案1】:

    您使用了不正确的值绑定。你应该在这里使用ngModel。 此外,您的单元格应该是一个对象,其中包含一些字段,其中包含一个数字。然后稍微改变你的模板:

    <div *ngFor="let cell of cells">
      <input [(ngModel)]="cell.field" type="number" [min]="0" [max] ="9" maxlength="1" class="row" (input)="onSearchChange()" >
    </div>
    

    【讨论】:

    • 我收到此错误 未捕获的错误:无法分配给引用或变量!
    • 那么你可能需要让你的单元格成为一个对象,里面有字段。并将ngModel 中的此字段用作cell.field。我将编辑我的答案。
    【解决方案2】:

    您可以使用[(ngModel)] 进行双向数据绑定,但不能使用模板引用变量。相反,您应该使用数组索引来引用 cells 项。为了使绑定正常工作,您还需要通过trackBy 的索引来跟踪项目,如this stackblitz 所示:

    <div *ngFor="let cell of cells; let i=index; trackBy: trackByIndex;">
      <input [(ngModel)]="cells[i]" type="number" [min]="0" [max]="9" maxlength="1" class="row" (input)="onSearchChange()">
    </div>
    

    用代码:

    export class LigneComponent implements OnInit {
    
      @Input() cells: Array<number>;
    
      ...
    
      trackByIndex(index: number, cell: any): any {
        return index;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 2015-09-09
      • 2021-07-03
      • 2019-06-14
      • 2018-04-14
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多