将组件化反应式表单输入的验证发送到另一个反应式表单

Send validation from a componentised ReactiveFrom input to another ReactiveForm

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

在我的示例 StackBlitz 中,已经存在基于表单验证对 disable/enable 搜索输入使用验证的逻辑。但是,既然我已经将其中一个输入移到它自己的组件中,那么出于验证目的而处于相同 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