angular - 在角度 8 ngFor 循环中更改结构时输入值保持不变
问题描述
我在 angular 8 ngFor 循环中遇到了一个奇怪的问题。
单击更新按钮后,weekValueDoubleArray 发生变化,但视图因旧输入数据而损坏。运行应用程序时,我从输入框中更改起始值,然后单击更新按钮。但是,即使在更新之后,更新前的更改值仍然存在。
<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);
}
}
}
解决方案
上面提到的观点<input type="text" [value]="weekValue">
是正确的,但我认为您可能还会遇到另一个问题,因为您使用的是数组数组。您的 HTML 中的值weekValue
可能绑定到数组数组的内部数组,然后当您替换外部数组时,与前一个内部数组的绑定仍然有效。
推荐阅读
- python - 如何在 sns.factorplot 中设置 x 轴的间隔?
- bezier - Kaplan-Meier 生存估计的核或贝塞尔曲线平滑
- typescript - 如何在 ngOnInit 上订阅两次?
- c# - 调用 RequestClientCredentialsTokenAsync 时,如何修复“对象引用未设置为对象的实例”?
- neo4j - 为什么不建议在图数据库中索引关系
- oracle - 插入语句中的 PL/SQL 绑定变量,
- php - 连接到 klick-tipp “API Zugriff verweigert”时出现 API 错误(拒绝访问)
- angular - 无法解析“@angular/material/typings/”
- .net - 在 PayPal 中执行付款后,我可以获得任何收款人的链接或交易 ID 吗?
- python - 在 PySpark 中添加滚动最新的列