在Angular中使用*ngFor
结合模板变量和双向绑定可以通过以下步骤实现:
*ngFor
指令来循环创建表单控件和其对应的模板变量。
import { Component } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent {
items = [{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }];
addItem() {
this.items.push({ name: '' });
}
deleteItem(index: number) {
this.items.splice(index, 1);
}
}
在模板中,使用*ngFor
循环创建表单控件时,为每个控件添加模板变量,并将其与数组中的对应项进行双向绑定。
使用[(ngModel)]
指令将表单控件的值与数组中的对应项进行双向绑定,以便在数组中的值发生变化时同步更新表单控件的值。
通过调用组件类中的方法,可以添加和删除数组中的项,从而实现动态添加和删除表单控件的功能。
以上就是使用*ngFor
结合模板变量和双向绑定实现动态添加和删除表单控件的解决方法。希望对你有帮助!