Angular 4 / Reactive Forms - 在子组件中添加控件

Angular 4 / Reactive Forms - Add Control in a child component

我有一个带有 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);
    }
    ...

但是两个"my input text"的值是一样的。我发现它是合乎逻辑的,因为它是我认为的相同表单控件。 所以,我在子组件的 OnInit 方法中尝试了另一种解决方案:

this.parent = this.formBuilder.group({ 
    textField: [this.model, conditionalRequired(this.required)]
});

在这种情况下,值是正确的,但我在我的 mainForm 中看不到这个控件。 我认为这是合乎逻辑的,因为我没有将我的控件添加到我的 parent/main 表单中。

我试图在官方文档页面上找到一些例子,但没有找到这个具体案例。 另一个解决方案应该是在我的主要组件的方法 BuildForm 中声明控件 textField 但我想找到另一个解决方案并在子组件中声明控件。

感谢您的帮助。

您不能像这样添加组件。您必须使用 factoryresolver 找到对组件的引用并添加它。 看看这个线程