简体   繁体   English

角度验证:单击按钮时验证/突出显示子输入

[英]Angular Validation: Validate/Highlight child input on button click

Using Angular 6 here:在此处使用 Angular 6:

I have a parent component and within that I have a child component.我有一个父组件,其中有一个子组件。 The child component has a text fields.子组件有一个文本字段。 The parent has a submit button.父级有一个提交按钮。

On the submit click button, I want to validate all the inputs of the child as they are required and throw error accordingly.在提交单击按钮上,我想根据需要验证孩子的所有输入并相应地抛出错误。

I am using reactive forms and was successfully able to pass form info from parent to child.我正在使用反应式表单并成功地将表单信息从父级传递给子级。 But I am not sure how to highlight my text input when the submit button is clicked.但是我不确定如何在单击提交按钮时突出显示我的文本输入。

I have used $touched property on my child, which works and shows the required error.我在我的孩子身上使用了 $touched 属性,它可以工作并显示所需的错误。 But I want the error to also show in case user just clicked the button.但我希望错误也显示在用户刚刚点击按钮的情况下。

Here is some relevant code.这是一些相关的代码。

--Parent--

<form class="form-horizontal" [formGroup]="myForm" (ngSubmit)="onSubmit()">
    <child [myForm]="myForm"></child>
  <button type="submit">Submit</button>
</form>

<br>
Form Valid:  <pre>{{myForm.valid}}</pre>

export class AppComponent {
  myForm: FormGroup

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      uname: ['', Validators.required]
    });
  }

  onSubmit() {
    console.log('value: ', this.myForm.value);
    console.log('the whole form and its controls: ', this.myForm)
  }
}

--Child--

<div class="form-group" [formGroup]="myForm">
    <label for="myForm" class="col-sm-3 control-label">Name:</label>
    <div class="col-sm-8" [ngClass]="{ 'has-error': myForm.controls?.uname.errors }">
      <input type="text" formControlName="uname"  placeholder="Enter Name...">
      <em *ngIf="myForm.hasError('required', 'uname') && myForm.controls?.uname.touched">*Required</em>
    </div>
  </div> 

export class ChildComponent {
  @Input() myForm: FormGroup;

  ngOnInit() {

  }
}

I have also created a demo to show this at:我还创建了一个演示来展示这一点:

https://stackblitz.com/edit/angular-dbevnj https://stackblitz.com/edit/angular-dbevnj

FYI, this is just a sample I created to show my issue.仅供参考,这只是我创建的一个示例来展示我的问题。 I would be having 2-3 child components and few form controls on each.我将有 2-3 个子组件,每个子组件都很少有表单控件。

Any inputs how to get this resolved?任何输入如何解决这个问题?

We resolved this by calling markAsTouched on all form controls when submitting the form.我们通过在提交表单时在所有表单控件上调用markAsTouched来解决这个问题。

In your case you can add this.myForm.get('uname').markAsTouched();在您的情况下,您可以添加this.myForm.get('uname').markAsTouched(); to your onSubmit() method.到您的onSubmit()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM