如何在自定义的组件(form 控件)中找到FormControl

本文探讨在Angular中如何解决因直接从依赖注入系统获取NgControl实例导致的循环依赖问题,通过使用Injector来绕过这一限制,实现自定义值访问器与NgControl的正确交互。

懒的翻译了,翻也翻不通顺,直接上原文(其实我就是个搬运工......)

As we can't get NgControl instance directly from DI system since we'll get a circular dependency error. The following diagram shows why it happens if we inject NgControl in our custom value accessor:

image

Now it should be clear that we have NgControl ->FormControlName ->ValueAccessor -> CustomValueAccessor -> NgControl circular dependency

To work around it you can leverageInjector to achieve that:

component.ts

import { NgControl } from '@angular/forms';
export class PasswordComponent implements ControlValueAccessor {
  ...
  ngControl: NgControl;

  constructor(private inj: Injector) {
    ...
  }

  ngOnInit() {
    this.ngControl = this.inj.get(NgControl)
  }

Plunker Example

转载于:https://www.cnblogs.com/hxling/articles/9525837.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值