javascript - 更改表行中的 [(ngModel)] 值将影响正文中存在的所有行。如何修复它?
问题描述
我有一个用 *ngFor 生成的表。现在在那个表里面我有 2 列和 5 行。第一列包含一个选择标签,第二列将显示选定的值。现在的问题是,当您在任何行的选择标记中选择任何值时,所选值会显示在所有行中。
为了更好地理解问题,请参阅https://stackblitz.com/edit/angular-43oxrc
app.component.ts
categoryCall(categoryName) {
if (categoryName == 1) {
this.categories = ["Value 1", "Value 2", "Value 3"];
}
else if (categoryName == 2) {
this.categories = ["Value 4", "Value 6", "Value 5", "Value 7"];
}
else if (categoryName == 3) {
this.categories = ["Value 7", "Value 8"];
}
return this.categories;
}
app.component.html
<table>
<tbody>
<tr *ngFor="let item of [1,2,3,4,5]">
<td>
<select [(ngModel)]="selectedCategory">
<option *ngFor="let category of categoryCall(item)" [ngValue]="category">{{category}}</option>
</select>
</td>
<td>
Choosen Value: {{selectedCategory}}
</td>
</tr>
</tbody>
</table>
我需要喜欢;如果您在第一行选择任何值,那么它的值应该只显示在它自己的第一行。它不应反映在任何其他行中
解决方案
你不能那样做。 原因是 selectedCategory 绑定到所有五个位置,因为它是一个值。你可以这样做。
TS
export class AppComponent {
selectedCategory: string;
categories: string[];
items = [];
constructor () {
this.addItems();
}
addItems() {
for (let i = 0; i < 5; i++) {
this.items.push({selectedCategory: null, number: i + 1});
}
}
}
HTML
<table>
<tbody>
<tr *ngFor="let item of items">
<td>
<select [(ngModel)]="item.selectedCategory">
<option *ngFor="let category of categoryCall(item.number)" [ngValue]="category">{{category}}</option>
</select>
</td>
<td>
Choosen Value: {{item.selectedCategory}}
</td>
</tr>
</tbody>
</table>
推荐阅读
- python - Visual Studio 代码的 Python 扩展不显示错误或警告消息
- tensorflow - 如何使用 TensorFlow BeamSearchDecoder?
- android - 有没有办法可以重新设计单选按钮
- r - ComplexHeatmap 对数刻度梯度
- r - R:存储包含循环的函数的输出(或删除循环)
- python - 使用 selenium 和 Python 与网页交互的问题
- reactjs - 我已将 styled-components 安装到我的 React 项目中,但出现错误
- github - 自动完成引导程序 4 源数据
- python - 使用 Sphinx 记录包 __init__ 导入
- substrate - 如何测试基板 3.0.0 中的事件?