如何动态更改Angular 10中的ngModel值



在Angular 10中,我动态生成三个下拉列表,需要动态生成它们的ngModel值(例如,row1、row2、row3(。

<table>
<tr *ngFor="let num of [0, 1, 2]; let i=index">
<td>
<h4>Row {{ num + 1 }}</h4>
<select matNativeControl [(ngModel)]="row[num+1]">
<option *ngFor="let item of items" [value]="item">{{ item.fruit }}</option>
</select>
</td>
</tr>
</table>

(ngModel)]="row[num+1]"是我试图在下拉列表相乘时添加1、2、3的地方。标头正在动态更改,但ngModel没有,并且由于发现row未定义而引发错误。我尝试了几种不同的方法,但都碰壁了。

这是来自app.component.ts:的代码

import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
row: any;
row1: any;
row2: any;
row3: any;
items: any;
num: any;
constructor() {}
ngOnInit(): void {
this.items = [
{ fruit: 'apple', color: 'red' },
{ fruit: 'orange', color: 'orange' },
{ fruit: 'grape', color: 'purple' }
];
}
// printVal() {
//   console.log('Test: ', this.row[this.num].fruit);
// }
}

这是stackblitz:https://stackblitz.com/edit/angular-ivy-9wr3vh

row[num]不等于row1。它正在搜索一个名为row的变量,然后它就是索引。由于你所在的行是未定义的,所以不可能将ngModel附加到它上。试试这样的方法,

import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
row = [0,1,2]
items: any;
constructor() {}
ngOnInit(): void {
this.items = [
{ fruit: 'apple', color: 'red' },
{ fruit: 'orange', color: 'orange' },
{ fruit: 'grape', color: 'purple' }
];
}
// printVal() {
//   console.log('Test: ', this.row[this.num].fruit);
// }
}

如果你想改变商品、颜色或水果,我不知道你想改变哪一种在你的html 中试试这个

<table>
<tr *ngFor="let item of items; let i=index">
<td>
<h4>Row {{ i + 1 }}</h4>
<select matNativeControl [(ngModel)]="item[i].color">
<option *ngFor="let item of items" [value]="item">{{ item.fruit }}</option>
</select>
</td>
</tr>
</table>

最新更新