I want to generate a reactive form from the tree structure.
Here is the code that creates the form items (form groups and controls). For the controls nested in form group it I use a recursive template.
import { Component, Input, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'form-item',
template: `
<ng-container [formGroup]="form">
<ng-container *ngTemplateOutlet="formItemTemplate; context:{ $implicit: pathSegments }"></ng-container>
<ng-template #formItemTemplate let-pathSegments>
<ng-container *ngIf="pathSegments.length > 1">
<div [formGroupName]="pathSegments[0]" class="form-group">
<ng-container *ngTemplateOutlet="formItemTemplate; context:{ $implicit: pathSegments.slice(1) }"></ng-container>
</div>
</ng-container>
<ng-container *ngIf="pathSegments.length === 1">
<div class="form-control">
<label>{{pathSegments[pathSegments.length - 1]}}</label>
<!--<input type="text" [formControlName]="pathSegments[pathSegments.length - 1]"/>-->
<input type="text"/>
</div>
</ng-container>
</ng-template>
</ng-container>
`,
})
export class AppControlComponent {
@Input() form: FormGroup;
@Input()
set path(path: string) {
this.pathSegments = path.split('.');
}
pathSegments: string[] = [];
constructor() { }
}
@Component({
selector: 'app-root',
template: `
<form [formGroup]="questionForm">
<h1>Question Form</h1>
<form-item [form]="questionForm" path="question"></form-item>
<form-item [form]="questionForm" path="answers.answer1"></form-item>
<form-item [form]="questionForm" path="answers.answer2"></form-item>
<form-item [form]="questionForm" path="answers.answer3"></form-item>
<button type="submit">submit</button>
<pre>{{questionForm.value | json}}</pre>
</form>
`,
})
export class AppComponent {
private questionForm: FormGroup;
constructor(private fb: FormBuilder) {
this.questionForm = this.fb.group({
question: ['', Validators.required],
answers: this.fb.group({
answer1: ['', Validators.required],
answer2: ['', Validators.required],
answer3: ['', Validators.required],
}),
});
}
}
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
declarations: [
AppComponent,
AppControlComponent
],
bootstrap: [AppComponent]
})
export class AppModule {}
The form HTML is generated perfectly. But when I add the formControlName
directive to the input the HTML generation breaks. Then I get such error:
Error: Cannot find control with name: 'answer1'
FormControlName
directive uses@Optional() @Host() @SkipSelf() parent: ControlContainer
to find parentformGroup
– SavellFormControlName
can findparent
in my template, can't it? TheFormGroupName
also uses that. – Westerly