如何使用模板表单从 Angular 2 中的父组件触发子组件验证器 [英] How to trigger child component validators from parent component in Angular 2 using template forms

查看:27
本文介绍了如何使用模板表单从 Angular 2 中的父组件触发子组件验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 中使用模板表单进行条件验证时遇到问题.我创建了一个自定义的 EmailInputComponent:

<label for="email">Email<span *ngIf="required">*</span></label><输入id="email"类=形式控制"名称=电子邮件"类型=电子邮件"[(ngModel)]="emailAddress"#email="ngModel"最大长度=255"验证电子邮件[required]="required ? '' : null"/><error [model]="email" [referencedValue]="emailAddress"></error>

托管在父 MyFormComponent 中:

<字段集><email [(emailAddress)]="model.email" [required]="emailRequired()"></email><!-- 在此处选择组件--></fieldset><button type="submit" [disabled]="!form.form.valid">发送</button></表单>

该表单还包含一个 SelectComponent,用户可以在其中选择他们喜欢的联系方式.如果用户选择电子邮件",则电子邮件输入变为必填项.

尽你所能,看到父级emailRequired中的一些逻辑函数,根据当前选择的首选联系方式动态计算电子邮件输入是否是强制性的.每当这个选定的值发生变化时,我需要以某种方式触发电子邮件输入验证器.我怎样才能做到这一点?

使用 @ViewChild 我设法从 MyFormComponent 中获取了 EmailInputComponent.但我现在不知道如何进行...

解决方案

同时我找到了解决方案.我的子组件现在引用相应的 FormGroup.

<email [(emailAddress)]="model.email"[formGroup]="form.form"[required]="emailRequired()"></电子邮件>

通过 FormGroup,您可以到达子组件实际 FormControl 并在验证器标志的设置器中调用 updateValueAndValidity(在我的情况下为set required):

import {Component, EventEmitter, Input, Output} from '@angular/core';从@angular/forms"导入{FormGroup};@成分({选择器:'电子邮件',templateUrl: './email.component.html',styleUrls: ['./email.component.css']})导出类 EmailInputComponent {私人_emailAddress:字符串;公共 _required = 真;@输入()私有表单组:表单组;@输出()emailAddressChange = new EventEmitter();构造函数(){}@输入()获取电子邮件地址():字符串{返回 this._emailAddress;}设置电子邮件地址(值:字符串){this._emailAddress = 值;this.emailAddressChange.emit(this._emailAddress);}@输入()获取必需():布尔{返回 this._required;}设置必需的(值:布尔值){this._required = 值;//这就是魔法发生的地方const refEmailControl = this.formGroup.controls.email;如果(refEmailControl){refEmailControl.updateValueAndValidity();//更新有效性状态refEmailControl.markAsTouched();//在我的情况下需要使 UI 呈现错误消息}}}

I'm having trouble with conditional validation using template forms in Angular. I've created a custom EmailInputComponent:

<div class="form-group" provide-parent-form>
  <label for="email">Email<span *ngIf="required">*</span></label>
  <input id="email"
         class="form-control"
         name="email"
         type="email"
         [(ngModel)]="emailAddress"
         #email="ngModel"
         maxlength="255"
         validateEmail
         [required]="required ? '' : null"/>
  <error [model]="email" [referencedValue]="emailAddress"></error>
</div>

which is hosted inside a parent MyFormComponent:

<form #form="ngForm" name="form" (ngSubmit)="onSubmit($event)">
  <fieldset>
    <email [(emailAddress)]="model.email" [required]="emailRequired()"></email> 
    <!-- select component here -->
  </fieldset>    
  <button type="submit" [disabled]="!form.form.valid">Send</button>
</form>

The form also contains a SelectComponent where users can choose their preferred way of contact. If users select "email", the email input becomes mandatory.

As you can, see there is some logic going on in the parents emailRequired function that dynamically calculates whether an email input is mandatory or not based on the currently selected preferred way of contact. Whenever this selected value changes I need to somehow trigger the email input validators. How can I do that?

Using @ViewChild I managed to get a hold of the EmailInputComponent from the MyFormComponent. But I don't know how to proceed now...

解决方案

Meanwhile I found a solution. My child component now references the according FormGroup.

<email [(emailAddress)]="model.email" 
       [formGroup]="form.form" 
       [required]="emailRequired()">
</email>

Via the FormGroup, you can then reach to the child components actual FormControl and call updateValueAndValidity inside the setter of the validator flag (set required in my case):

import {Component, EventEmitter, Input, Output} from '@angular/core';
import {FormGroup} from '@angular/forms';

@Component({
  selector: 'email',
  templateUrl: './email.component.html',
  styleUrls: ['./email.component.css']
})
export class EmailInputComponent {

  private _emailAddress: string;

  public _required = true;

  @Input()
  private formGroup: FormGroup;

  @Output()
  emailAddressChange = new EventEmitter();

  constructor() { }

  @Input()
  get emailAddress(): string {
    return this._emailAddress;
  }

  set emailAddress(value: string) {
    this._emailAddress = value;
    this.emailAddressChange.emit(this._emailAddress);
  }

  @Input()
  get required(): boolean {
    return this._required;
  }

  set required(value: boolean) {
    this._required = value;
    // this is where the magic happens
    const refEmailControl = this.formGroup.controls.email;
    if (refEmailControl) {
      refEmailControl.updateValueAndValidity(); // updates the validity state      
      refEmailControl.markAsTouched(); // necessary in my case to make UI render error message
    }
  }
}

这篇关于如何使用模板表单从 Angular 2 中的父组件触发子组件验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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