Jeyabalan Thavamani
Jeyabalan Thavamani

Reputation: 3327

Angular 5 Form validation and display error in generic component

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?

Upvotes: 1

Views: 1051

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29715

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>

Upvotes: 1

Related Questions