下面是一个使用ngModel将动态绑定到索引数组的解决方法的示例代码:
在组件HTML文件中:
在组件TS文件中:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
items: string[] = [];
addItem() {
this.items.push('');
}
}
在上面的示例中,我们使用ngFor指令在HTML模板中循环遍历items数组,并使用ngModel指令将每个输入框与数组的对应索引项进行双向绑定。通过点击按钮,可以动态地在数组中添加新项。
请注意,该示例仅适用于单个输入框的情况。如果需要绑定多个属性,可以使用对象数组或创建一个包含多个属性的自定义对象数组。