2
votes

I Have nested reactive form, like below

parent HTML

<form>
 <child></child>
 <button mat-raised-button color="primary">Save</button>
</form>

child HTML

<div [formGroup]="headerSection">
 <input type="text" formControlName="test">
 <!span [hidden]="headerSection.get('test').valid">required</span> 
</div>

I want to throw error message in child HTML, but when clicking the parent submit button...

2
I guess <!span> is a typoJota.Toledo
hey! did either answer help you, or is there some trouble still? :)AT82

2 Answers

2
votes

I don't see that you are actually passing formgroup to your child? So do that first, then I would add another input, a boolean value that is set to true when form has been submitted.

So your parent ts:

submitted = false;

this.myForm = this.fb.group({
  test: ['', Validators.required]
});

Child tag:

<child [headerSection]="myForm" [submitted]="submitted"></child>

Then in your child show the form and add the conditions on when to show/hide the validation messages:

@Input() headerSection: FormGroup;
@Input() submitted: boolean;

Html:

<div [formGroup]="headerSection">
  <input type="text" formControlName="test">
  <span *ngIf="!headerSection.controls.test.valid && submitted">required</span> 
</div>

Finally a DEMO

0
votes

in angular 2 you must create child's elements as a component with @Input & @Output (as a Emmiter) fields for interaction with parent component.