I'm trying to build a data-driven form, with inputs coming from another component, like this:
<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<app-form-group [name]="name"></app-form-group>
<app-form-group [name]="email"></app-form-group>
<app-form-group [name]="other"></app-form-group>
</form>
The app-form-group
component will look something like this:
<div class="form-group">
<label class="col-md-2 control-label">{{Name}}</label>
<div class="col-md-9">
<input class="form-control" [name]="name" [formControlName]="formCtrlName">
</div>
The problem is that formControlName
needs a formGroup
directive, therefore I get this error:
Error : Error in ./FormGroupComponent class FormGroupComponent - inline template:3:58 caused by: formControlName must be used with a parent formGroup directive.You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
Is there any way to get around this issue?
You should use your FormGroup
[formGroup]="signupForm"
inapp-form-group
Component.You can use this Code :When you want to implement a custom component for data-binding to an individual value the correct Angular way to do that is to go with the approach where the parent view specifies either
[formControl]
or[formControlName]
.In your child control you need to do the following:
First add the following provider to your
@Component
declaration, so Angular knows your component can work with[formControlName]
/[formControl]
Your child component's class then needs to implement the
ControlValueAccessor
interface. This should be a fully working example, if not then let me know and I will change the code, I typed it into the browser directly.Your
app-form-group
template would look something like this[formGroup]="signupForm"
to each of yourapp-form-group
instances in your main viewapp-form-group
control.private controlContainer: ControlContainer
to the constructor of yourapp-form-group
component so Angular will inject itpublic form: FormGroup;
property to yourapp-form-group
component.In ngOnInit add the following code
this.form = this.containerControl.control;
In your
app-form-group
template you would add [formGroup] like soThis is the method that requires the least amount of code, and is the one I would recommend when you want to embed composite controls that edit multiple pieces of data (like an Address).
From this blog -> https://mrpmorris.blogspot.co.uk/2017/08/angular-composite-controls-formgroup-formgroupname-reactiveforms.html
You can use a @Input property to get the reference into the sub-component:
app-form-group.ts:
app.html:
app-form-group.html:
For detailed information have a look at this tutorial: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2