Send validation from a componentised ReactiveFrom input to another ReactiveForm(将验证从组件化的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将验证从组件化的Reactive From输入发送到另一个Reactive Form
基础教程推荐
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
