有人可以帮助我吗?我有两个组件“父级”和“子级”。在父组件中,我有这个 formGroup 和两种获取人和城市的方法。
ngOnInit() {
this.form = this.fb.group({
person: this.fb.group({
name: new FormControle(''),
age: new FormControle(''),
}),
city: this.fb.group({name: new FormControl('')})
})
}
get person(): FormGroup {
return this.form.get('person') as FormGroup;
}
get city(): FormGroup {
return this.form.get('city') as FormGroup;
}
我想像这样在子组件中获取 Person FormGroup
<app-child-component [form]="person"></app-child-component>
和现场子组件我有这样的 html 组件
<form [formGroup]="form">
<input type="text" formControlName="name"/>
</form>
在 component.ts 子组件中我有
@Input() form: FormGroup;
一切正常,但在控制台中出现错误错误:NG01203:没有表单控件名称的值访问器:'name'
如果我制作console.log(this.form);在子组件中,形式是定义的。
我认为您缺少父组件上的表单包装器,我们还需要使用
formGroupName
将组件包装在 div 内,指定它属于人员表单组。
<form [formGroup]="form">
<div formGroupName="person">
<app-child [form]="person"/>
</div>
<div formGroupName="city">
<input type="text" formControlName="name"/>
</div>
</form>
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
FormBuilder,
FormControl,
FormGroup,
ReactiveFormsModule,
} from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
@Component({
selector: 'app-child',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<input type="text" formControlName="name"/>
<input type="text" formControlName="age"/>
</form>
`,
})
export class Child {
@Input() form!: FormGroup;
}
@Component({
selector: 'app-root',
standalone: true,
imports: [Child, ReactiveFormsModule, CommonModule],
template: `
<form [formGroup]="form">
<div formGroupName="person">
<app-child [form]="person"/>
</div>
<div formGroupName="city">
<input type="text" formControlName="name"/>
</div>
</form>
{{form.value | json}}
`,
})
export class App {
form: FormGroup = new FormGroup({});
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
person: this.fb.group({
name: new FormControl(''),
age: new FormControl(''),
}),
city: this.fb.group({ name: new FormControl('') }),
});
}
get person(): FormGroup {
return this.form.get('person') as FormGroup;
}
get city(): FormGroup {
return this.form.get('city') as FormGroup;
}
}
bootstrapApplication(App);