将验证从组件化的Reactive From输入发送到另一个Reactive Form [英] Send validation from a componentised ReactiveFrom input to another ReactiveForm

查看:34
本文介绍了将验证从组件化的Reactive From输入发送到另一个Reactive Form的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在传统的Reactive Form中,您可以指定所有输入,并在相关组件的HTML文件上为这些输入添加FormControl和验证。我正在将其中一些输入移动到它们自己的组件中,以便它们变得可共享和可重复使用。

在我的示例StackBlitz中,已经存在使用验证来禁用/启用基于表单验证的搜索输入的逻辑。但是,现在我已经将其中一个输入移动到它自己的组件中,出于验证目的而处于相同formBuilder表单中的关系不再适用。

Component.ts

this.registerForm = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
     // password: ['', [Validators.required, Validators.minLength(6)]]
    });
我已经注释掉了密码输入,因为我不再在此表单中构建它,但我仍然想知道它的验证并将其应用于此表单,以便只有在填写完所有3个输入并通过验证规则后才能启用搜索。目前,您只需填写名字和姓氏即可启用搜索输入域。

密码现在如下所示: HTML

<password-input label="Password" [value]=""></password-input>

推荐答案

我们可以在密码输入组件中注入ControlContainer来访问parentFormgroup。然后,我们可以将密码表单控件动态添加到现有的FormGroup。

Component.ts

import { Component, OnInit, Input } from '@angular/core';
import { ControlContainer, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'password-input',
  templateUrl: './passwordinput.component.html'
})
export class PasswordInputComponent implements OnInit {
  @Input('value') value = '';
  @Input('label') label = 'test label';
  control: FormControl;
  formGroup:FormGroup;
  constructor(private controlContainer:ControlContainer) {}

  ngOnInit() {
    const parentForm = (this.controlContainer['form'] as FormGroup);
    parentForm.addControl('password',new FormControl(this.value,[Validators.required, Validators.minLength(6)]));
    this.control = parentForm.get('password') as FormControl;
  }
}

Component.html

<div class="form-group">
  <label>Password</label>
  <input type="password" [formControl]="control" class="form-control" />
</div>

Working Example

这篇关于将验证从组件化的Reactive From输入发送到另一个Reactive Form的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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