我如何知道自定义表单控件何时在Angular中标记为pristine?

我如何知道自定义表单控件何时在Angular中标记为pristine?,第1张

概述我的Angular应用程序中有几个自定义表单控件组件,它们实现了ControlValueAccessor接口,效果很好. 但是,当在父表单上调用markAsPristine()时,或直接在我的自定义控件上调用时,我需要更新它的状态:我的自定义控件实际上有内部控件,我也需要在其上调用markAsPristine(). 那么,我如何知道何时在我的控件上调用markAsPristine()? Contr 我的Angular应用程序中有几个自定义表单控件组件,它们实现了ControlValueAccessor接口,效果很好.

但是,当在父表单上调用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?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1074834.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存