Angular 5表单验证和通用组件中的显示错误 [英] Angular 5 Form validation and display error in generic component

查看:74
本文介绍了Angular 5表单验证和通用组件中的显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用组件,如下所示,

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>

然后是我的json

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

基于上述json,如果我想验证两个输入字段,然后显示相应输入字段的错误,则应用程序组件将对其进行迭代并呈现输入框.我不知道如何使用表格来处理它?

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?

推荐答案

在父级app-component

myForm : FormGroup

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

,然后将其作为输入传递给子组件.

and then pass that as an input to child component.

所以您必须在子组件中声明@Input() myForm : FormGroup

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

父项

<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))
}

子组件

 <form [formGroup]="myForm">
   <input type="text" 
    [formControlName]="someName"
    [id]="data.name"/>
</form>
<error-message [message]="message"></error-message>

这篇关于Angular 5表单验证和通用组件中的显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆