我正在尝试使用 Angular 创建动态表单,我可以将模型类传递给自定义 DynamicFormComponent 并让它根据类属性生成表单字段。但是,我面临一个问题,即使用 DynamicFormComponent 时未显示表单字段。
这是我的代码设置:
动态表单.component.ts:
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: '',
})
export class DynamicFormComponent implements OnInit {
@Input() modelClass: any;
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
const modelInstance = new this.modelClass();
const formControlsConfig: Record<string, any> = {};
Object.keys(modelInstance).forEach((key) => {
formControlsConfig[key] = new FormControl();
});
this.form = this.fb.group(formControlsConfig);
}
onSubmit() {
if (this.form.valid) {
const modelInstance = new this.modelClass();
Object.assign(modelInstance, this.form.value);
console.log(modelInstance);
}
}
}
app.component.html:
<h1>Dynamic Form Example</h1>
<app-dynamic-form [modelClass]="'Person'"></app-dynamic-form>
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { DynamicFormComponent } from './dynamic-form/dynamic-form.component';
import { Person } from './person.model';
@NgModule({
declarations: [AppComponent, DynamicFormComponent],
imports: [BrowserModule, ReactiveFormsModule],
bootstrap: [AppComponent],
})
export class AppModule {}
问题是,当我在模板中使用 DynamicFormComponent 时,它会正确呈现组件,但不显示表单字段。我已经仔细检查了我的代码,检查了依赖关系,并尝试了不同的方法,但我似乎无法确定导致问题的原因。
任何人都可以帮助我理解为什么表单字段没有使用 DynamicFormComponent 显示吗?任何见解或建议将不胜感激。
您没有共享 app.component.ts 代码,但我们假设它是这样的:
@Component({
templateUrl: './app.component.html'
})
export class AppComponent {
person: Person;
constructor () {
this.person = new Person();
this.person.firstName = 'John';
this.person.lastName = 'Doe';
}
}
AppComponent类的HTML代码:
<h1>Dynamic Form Example</h1>
<app-dynamic-form [modelClass]="person"></app-dynamic-form>
这里的关键是HTML代码中的
[modelClass]="person"
部分。当您在传递 Angular 自定义组件输入属性的值时使用方括号时,这意味着您传递给它的值是 Typescript/JavaScript 表达式(例如组件属性)。因此,在此示例中,我们传递 AppComponent 的 person
属性值。
您的问题是您传递了“'Person'”,这意味着您将“Person”文本传递给了 modelClass 属性,因为“Person”是字符串文字。您必须删除双引号内的单引号才能传递表达式。