首页 > 解决方案 > 在角度 8 ngFor 循环中更改结构时输入值保持不变

问题描述

我在 angular 8 ngFor 循环中遇到了一个奇怪的问题。

单击更新按钮后,weekValueDoubleArray 发生变化,但视图因旧输入数据而损坏。运行应用程序时,我从输入框中更改起始值,然后单击更新按钮。但是,即使在更新之后,更新前的更改值仍然存在。 这是在编辑文本之前

这是在编辑文本之后

这是点击更新按钮后 这是html代码:

<div class="table-responsive mb-4 mt-4">
  <button (click)="update()">update</button>

  <table class="table table-bordered custom-table" id="mytable">
    <tr id="headerRow">
      <ng-container *ngFor="let wk of arrayOfWeeks;let i=index">
        <th id="arrayWks{{i}}">{{wk}}</th>
      </ng-container>
    </tr>
    <ng-container id="ngId" *ngFor="let currSample of currentSamples;let in=index">
      <tr>
        <ng-container *ngFor="let weekValue of weeksValueDoubleArray[in];let i=index">
          <td>
            <input type="text" value={{weekValue}}>
          </td>
        </ng-container>
      </tr>
    </ng-container>
  </table>
</div>

打字稿代码如下:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  public currentSamples: string[];
  public arrayOfWeeks: string[];
  public weeksValueDoubleArray: string[][];
  public weeksValue: string[];
  constructor() { }

  ngOnInit() {
    this.currentSamples = new Array();
    this.currentSamples.push("0", "1", "2", "3", "4");
    this.populateWeeksValue();
    this.arrayOfWeeks = new Array();
    for (var i = 1; i <= 54; i++) {
      if (i < 10) {
        this.arrayOfWeeks.push("WW0" + String(i));
      }
      else {
        this.arrayOfWeeks.push("WW" + String(i));
      }
    }
  }

  update() {
    this.weeksValueDoubleArray = [];
    for (let ind = 0; ind < this.currentSamples.length; ind++) {
      this.weeksValue = new Array();
      for (var i = 1; i < 54; i++) {
        let value = "";
        if (i > 31 && i < 40) {
          value = "yes";
        }
        this.weeksValue.push(value);
      }
      this.weeksValueDoubleArray.push(this.weeksValue);
    }
  }
  populateWeeksValue() {
    this.weeksValueDoubleArray = [];
    for (let ind = 0; ind < this.currentSamples.length; ind++) {
      this.weeksValue = new Array();
      for (var i = 1; i < 54; i++) {
        let value = "";
        if (i > 21 && i < 30) {
          value = "yes";
        }
        this.weeksValue.push(value);
      }
      this.weeksValueDoubleArray.push(this.weeksValue);
    }
  }
}

标签: angularngfor

解决方案


上面提到的观点<input type="text" [value]="weekValue">是正确的,但我认为您可能还会遇到另一个问题,因为您使用的是数组数组。您的 HTML 中的值weekValue可能绑定到数组数组的内部数组,然后当您替换外部数组时,与前一个内部数组的绑定仍然有效。


推荐阅读