【发布时间】:2018-01-16 13:27:45
【问题描述】:
我有一个带有 FormGroup 的父组件。 在我的 html 代码中,我多次调用了一个名为 my-text-input 的子组件,例如。 在这个子组件中,我有一个带有特定属性 FormControlName 的输入文本。 我想将此控件添加到我的主窗体中。
我使用 formGroup 的主要组件:
<form class="form-horizontal" [formGroup]="mainForm" (ngSubmit)="save()"
novalidate>
<div class="devis-container">
...
<!-- first call of my child component -->
<my-input-text [parent]="mainForm" [model]="myObject.name" class="size-xl"
[required]="true"></my-input-text>
...
<!-- and in another part of the main form, another declaration -->
<my-input-text [parent]="mainForm" [model]="myObject.surname" class="size-
xl" [required]="true"></my-input-text>
...
</div>
</form>
我的子组件的 HTML:
<form [formGroup]="parent" name="inputTextForm">
<input type="text" formControlName="textField" placeholder="{{placeholder}}" class="domia-input"/>
...
</form>
所以我的问题是我不知道如何将控件“textField”添加到我的主窗体中。 我试过这个:
export class MyInputTextComponent extends InputBaseComponent implements OnInit {
...
@Input()
parent: FormGroup;
...
ngOnInit() {
this.parent.addControl('textField',
new FormControl('',
Validators.compose([conditionalRequired(this.required),
Validators.pattern(this.regex),
Validators.minLength(this.minlength),
Validators.maxLength(this.maxlength)]))
);
this.parent.controls.textField.setValue(this.model);
}
...
但是两个“我的输入文本”的值是一样的。我发现这是合乎逻辑的,因为它与我认为的表单控件相同。 因此,我在子组件的 OnInit 方法中尝试了另一种解决方案:
this.parent = this.formBuilder.group({
textField: [this.model, conditionalRequired(this.required)]
});
在这种情况下,值没问题,但我在 mainForm 中看不到这个控件。 我认为这是合乎逻辑的,因为我没有将控件添加到我的父/主窗体中。
我试图在官方文档页面上找到一些示例,但我没有找到这个具体案例。 另一种解决方案应该是在我的主组件的方法 BuildForm 中声明控件 textField 但我想找到另一种解决方案并在子组件中声明控件。
感谢您的帮助。
【问题讨论】:
-
听起来你应该拥有一个
FormArray,并且对于每个FormControls,你将创建这个表单控件。
标签: angular angular-reactive-forms