gpt4 book ai didi

angular - Angular2 中自定义指令的 NgControl

转载 作者:行者123 更新时间:2023-12-04 18:00:16 26 4
gpt4 key购买 nike

我正在尝试在自定义组件上使用 ngControl。我已经创建了组件并在组件上实现了 ControlValueAccessor

然后在构造函数中,注入(inject) NgControl 如下:

constructor(@Self() private ngControl: NgControl){
this.ngControl.valueAccessor = this;
}

但是当我在选择器上使用 ngControl 时,表单类(ng-pristine、ng-touched、ng-invalid)不会更新,我也无法检查表单元素。

任何人都可以帮助我做错了什么。


添加到问题描述中我试过 Thierry Templier解决方案,由于对 angular2 的了解有限,但我遇到了循环引用错误。

在问题中详细说明,当我在容器组件中使用 ngControl 时,我有一个组件 MyComponent,我在 ContainerComponent 中使用它,根据 Thierry Templier 描述的对 MyComponent 所做的更改,我得到了循环引用错误,类似于:(MyComponent -> ngControl ..... -> token** ->我的组件).

关于这方面的任何建议。

最佳答案

事实上,您需要将您的值访问器注册到组件的提供程序中。请注意,它可以是它自己:组件是值访问器,需要在其提供者中自行注册)。事实上,这种情况 forwardRef 很有用。

类似的东西:

const CUSTOM_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => LabelsValueAccessor), multi: true});

@Component({
(...)
providers: [CUSTOM_VALUE_ACCESSOR]
})
export class LabelsValueAccessor implements ControlValueAccessor {
(...)
}

关于angular - Angular2 中自定义指令的 NgControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36283215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com