在Angular中,使用ng-template和form-group可以动态生成表单控件,以下是一个示例解决方法:
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
@ViewChild('myForm') myForm: any; // 获取ng-template的引用
onSubmit() {
// 获取ng-template中的表单控件的值
const formValue = this.myForm.nativeElement.value;
console.log(formValue);
}
}
这样,当用户提交表单时,ngSubmit事件将触发组件中的onSubmit方法,你可以在该方法中获取ng-template中表单控件的值,并进行相应的处理。