Angular 5 Form validation and display error in generic component

那年仲夏 提交于 2019-12-23 03:26:05

问题


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?


回答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>


来源:https://stackoverflow.com/questions/51281527/angular-5-form-validation-and-display-error-in-generic-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!