我如何知道自定义表单控件何时在 Angular 中被标记为原始控件? [英] How do I know when custom form control is marked as pristine in Angular?

查看:27
本文介绍了我如何知道自定义表单控件何时在 Angular 中被标记为原始控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Angular 应用程序中有几个自定义表单控件组件,它们实现了 ControlValueAccessor 接口并且效果很好.

I have several custom form control components in my Angular application, which implement ControlValueAccessor interface and it works great.

但是,当在父窗体上调用 markAsPristine() 或直接在我的自定义控件上调用时,我需要更新它的状态:我的自定义控件实际上具有内部控制,我需要调用 markAsPristine() 也在上面.

However, when markAsPristine() is called on parent form, or on my custom control directly I need to update it's state: my custom control is actually have internal control and I need to call markAsPristine() on it too.

SO,我怎么知道何时在我的控件上调用了 markAsPristine()?

ControlValueAccessor 接口没有成员,与这个问题相关,我可以实现.

The ControlValueAccessor interface has no members, related to this problem, which I can implement.

推荐答案

经过彻底调查后,我发现此功能并非由 Angular 专门提供.我已经在官方存储库中发布了一个问题,并且已获得功能请求状态.我希望它会在不久的将来实施.

After thorough investigation I've found out that this functionality is not specifically provided by Angular. I've posted an issue in the official repository regarding this and it's gained feature request status. I hope it will be implemented in near future.

在那之前,这里有两种可能的解决方法:

@Component({
  selector: 'my-custom-form-component',
  templateUrl: './custom-form-component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: MyCustomFormComponent,
    multi: true
  }]
})
export class MyCustomFormComponent implements ControlValueAccessor, OnInit {

  private control: AbstractControl;


  ngOnInit() {
    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',
  templateUrl: './custom-form-component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: MyCustomFormComponent,
    multi: true
  }]
})
export class MyCustomFormComponent implements ControlValueAccessor, 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 实例,请参阅此问题:获取访问权限从 Angular 中的自定义表单组件到 FormControl.


And if you need to access the FormControl instance from your component, please see this question: Get access to FormControl from the custom form component in Angular.

这篇关于我如何知道自定义表单控件何时在 Angular 中被标记为原始控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆