1

I have a generic component like below,

// selector: 'app-text-box'
<form>
   <input type="text" 
    [name]="data.name"
    [id]="data.name"/>
</form>
<error-message [message]="message"></error-message>

Also my app component like below,

<div *ngFor="let data of jsonData | async">

  <app-text-box [data]="data"
            *ngIf="data.type === 'TEXT'">
  </app-text-box>

</div>

And then my json

[
 {
    "type": "TEXT",
    "name": "book"
 },
 {
    "type": "TEXT",
    "name": "note"
 }
]

based on the above json, the app component will iterate it and render the input box, if I want to validate the both input field and then display error for corresponding input field. I don't know how to handle it using form?

6
  • I have added an answer describing the solution to your problem. Let me know if you need any clarification on that. Commented Jul 11, 2018 at 10:50
  • I'm getting 'ERROR TypeError: Cannot read property 'addControl' of undefined' for this line 'this.myForm.addControl('someName', new FormControl(data.name, Validators.required))' Commented Jul 11, 2018 at 11:57
  • Sorry Add that code in your ngOnInit() not in constructor. I have just given you the design flow. Its not a complete code. You can definitely work it out Commented Jul 11, 2018 at 12:18
  • Working fine as expected, Thanks :) Commented Jul 11, 2018 at 16:20
  • Moreover how to validate server response failure using angular 5 form validation? Commented Jul 12, 2018 at 8:45

1 Answer 1

1

Create a form object in your parent app-component say

myForm : FormGroup

constructor(private fb : FormBuilder) {
   this.myForm = this.fb.group({});
}

and then pass that as an input to child component.

So you have to declare @Input() myForm : FormGroup in child component

parent comp

<form [formGroup]="myForm">
     <app-text-box [data]="data" [myForm]="myForm"
            *ngIf="data.type === 'TEXT'">
     </app-text-box>
</form>   
{{myForm.valid}} -- prints true or false

An In your child component, add input controls to the same form group passed by parent

constructor(fb : FormBuilder) {
     // add input controls to the same form group
    this.myForm.addControl('someName', new FormControl(data.name, Validators.required))
}

child component

 <form [formGroup]="myForm">
   <input type="text" 
    [formControlName]="someName"
    [id]="data.name"/>
</form>
<error-message [message]="message"></error-message>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.