【问题标题】:Send validation from a componentised ReactiveFrom input to another ReactiveForm将验证从组件化的反应式表单输入发送到另一个反应式表单
【发布时间】:2021-09-29 01:36:36
【问题描述】:

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

在我的示例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>

【问题讨论】:

    标签: javascript angular forms angular-reactive-forms reactive-forms


    【解决方案1】:

    我们可以在密码输入组件中注入 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

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多