forms – 从自定义组件中设置Angular 2控件的有效性
发布时间:2020-12-17 07:28:29 所属栏目:安全 来源:网络整理
导读:我有一个自定义的Ng2组件,我正在使用模型驱动的方法. form [ngFormModel]="myForm" class="layout vertical relative" my-custom-comp ngControl="currentValue"/my-custom-comp/form 因此,在我的自定义组件中,我拥有我需要的所有逻辑,但我找不到一种方法来
我有一个自定义的Ng2组件,我正在使用模型驱动的方法.
<form [ngFormModel]="myForm" class="layout vertical relative"> <my-custom-comp ngControl="currentValue"></my-custom-comp> </form> 因此,在我的自定义组件中,我拥有我需要的所有逻辑,但我找不到一种方法来获取对ngControl的引用,以将其设置为有效或无效的自定义组件内部.
您可以查看此链接以获取工作示例:
https://github.com/byavv/angular2-playground/tree/master/client/app/modules/forms_explore
一些关键方面: export class Datepicker implements ControlValueAccessor { 在组件中注入ngControl并注册它: constructor(private ngControl:NgControl) ngControl.valueAccessor = this; 在组件中,您应该有一个验证字段的表单,以便您可以订阅以发出正确的值或设置父ngControl表单的错误. this.dateForm = builder.group({ dateControl: ['',Validators.compose([Validators.required,CustomValidators.frenchDate])],}); this.dateForm.valueChanges .subscribe((val) => { if (this.dateForm.valid) { this.onChange.emit(this.dateToTimestamp(val.dateControl)); } else { this.ngControl.control.setErrors({ "wrongDate": true }); } }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |