但是,当在父表单上调用markAsPristine()时,或直接在我的自定义控件上调用时,我需要更新它的状态:我的自定义控件实际上有内部控件,我也需要在其上调用markAsPristine().
那么,我如何知道何时在我的控件上调用markAsPristine()?
ControlValueAccessor接口没有与此问题相关的成员,我可以实现它.
解决方法 经过彻底调查后,我发现Angular并未特别提供此功能.我在官方存储库中有 posted an issue这个,它获得了功能请求状态.我希望它能在不久的将来实施.在此之前,这里有两种可能的解决方法:
猴子修补标记AsPristine()
@Component({ selector: 'my-custom-form-component',templateUrl: './custom-form-component.HTML',provIDers: [{ provIDe: NG_VALUE_ACCESSOR,useExisting: MyCustomFormComponent,multi: true }]})export class MyCustomFormComponent implements NG_VALUE_ACCESSOR,OnInit { private control: AbstractControl; ngOnInit () { const self = this; const origFunc = this.control.markAsPristine; this.control.markAsPristine = function () { origFunc.apply(this,arguments); console.log('Marked as pristine!'); } }}
使用ngDoCheck监视更改
请注意,此解决方案可能性能较差,但它可以为您提供更好的灵活性,因为您可以监控原始状态何时发生变化.在上面的解决方案中,只有在调用markAsPristine()时才会通知您.
@Component({ selector: 'my-custom-form-component',DoCheck { private control: AbstractControl; private pristine = true; ngDoCheck (): voID { if (this.pristine !== this.control.pristine) { this.pristine = this.control.pristine; if (this.pristine) { console.log('Marked as pristine!'); } } }}
如果您需要从组件访问FormControl实例,请参阅此问题:Get access to FormControl from the custom form component in Angular.
总结以上是内存溢出为你收集整理的我如何知道自定义表单控件何时在Angular中标记为pristine?全部内容,希望文章能够帮你解决我如何知道自定义表单控件何时在Angular中标记为pristine?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)