您可以使用Angular的Mat-Table组件来实现将每一行作为独立的表单的功能。以下是一个示例代码:
npm install @angular/material @angular/cdk @angular/animations
import { NgModule } from '@angular/core';
import { MatTableModule } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
@NgModule({
imports: [
MatTableModule,
MatInputModule,
MatButtonModule
],
exports: [
MatTableModule,
MatInputModule,
MatButtonModule
]
})
export class MaterialModule { }
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
export interface FormRow {
name: string;
email: string;
phone: string;
formGroup: FormGroup;
}
@Component({
selector: 'app-form-table',
templateUrl: './form-table.component.html',
styleUrls: ['./form-table.component.css']
})
export class FormTableComponent {
dataSource: FormRow[] = [];
constructor() {
// 添加表单数据
this.addRow();
}
addRow() {
// 创建表单组并添加到数据源中
const formGroup = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
phone: new FormControl('')
});
const newRow: FormRow = {
name: '',
email: '',
phone: '',
formGroup: formGroup
};
this.dataSource.push(newRow);
}
removeRow(index: number) {
// 从数据源中删除行
this.dataSource.splice(index, 1);
}
}
Name
Email
Phone
在上述示例中,我们使用了Angular的Reactive Forms来创建表单控件和表单组。每一行都有一个