Reputation: 399
My Angular app consist of one large form. I am able to capture the values from each field & post it to a server.
But now, I am trying to re-factor the app into several child components. I am having the below issue with ngModel when I try to create a child component.
I have created a child component (selector: app-terms-conditions).
Here is the child component code:
terms-conditions.component.html
<card>
<card-heading>
<card-heading-body>
<h4>Header content</h4>
</card-heading-body>
</card-heading>
<card-body>
Body content
</card-body>
<card-footer>
<checkbox
id="accept"
heading="I accept"
name="accept"
value="accept"
[(ngModel)]="chkAcceptTerms"
required
#theChkAcceptTerms="ngModel">
</checkbox>
</card-footer>
</card>
Here is where I'm displaying this child component in the parent component:
<accordion-body>
<app-terms-conditions></app-terms-conditions>
</accordion-body>
I currently get the following error in terms-conditions.component.html:
Identifier 'chkAcceptTerms' is not defined. The component declaration, template variable declarations, and element references do not contain such a member
This is just one of several child components I have.
I want to capture the selected values from the various child components & post them all together to a server.
Here is an example of some code in the parent component that uses this checkbox before the re-factoring:
this.postData(this.chkAcceptTerms, ...);
But I don't know if I should pass the values from the child components to the parent, or how to even do that, or is there a better approach?
Can someone please advise me, or perhaps give a concrete example? Any help is much appreciated!
Upvotes: 0
Views: 469
Reputation: 864
I think you should go with Reactive forms
in angular.
First define a form group in service.
this.formName = this.formBuilder.group({
chkAcceptTerms: ['']
})
and then share this service across child components:
<card-footer [form]="formName">
<checkbox
id="accept"
heading="I accept"
name="accept"
value="accept"
formControlName="chkAcceptTerms"
required>
</checkbox>
</card-footer>
More information here
Upvotes: 1