Using Angular 6 here:
I have a parent component and within that I have 3 child components. The child 1 component has a text fields, child 2 component has a dropdown and child 3 component has a dropdown and a submit button.
On the submit click button of child 3, I want to validate all the inputs of child1, child2 and child3 as they are required and throw error accordingly.
With angularjs I can just bind to ngmodel and check if form is invalid. How can I do so in angular? I mean how can I get and pass the state of input from one child to another etc. When searching I found the concept of reactive forms but most of the articles are of parents forms having input only.
Would appreciate if anyone can provide help on this. Below is the code I have
--Updated--
I updated below code after following this post: https://medium.com/@joshblf/using-child-components-in-angular-forms-d44e60036664
But this one keeps on giving me error in console: "Error: 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)."
--Updated code with reactive form--
--Parent--
<form class="form-horizontal" [formGroup]="myForm">
<div class="row">
<ct-child1 [myForm]="myForm"></ct-child1>
<ct-child2> </ct-child2>
</div>
<div class="row">
<ct-child3></ct-child3>
</div>
</form>
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'ct-parent',
templateUrl: './parent.component.html']
})
export class ParentComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
uname: ['', Validators.required]
});
}
}
--Child 1--
<div class="panel-body">
<div class="form-group">
<label for="myForm" class="col-sm-3 control-label">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="uname" [formControlName]="'uname'" placeholder="Enter Name..." required >
</div>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'ct-child1',
templateUrl: './child1.component.html']
})
export class Child1Component implements OnInit {
@Input() myForm: FormGroup;
constructor() { }
uname: string;
ngOnInit() { }
}