问题描述
我在Angular应用程序中有一个自定义的表单控件组件,该组件实现了ControlValueAccessor
接口.
I have a custom form control component in my Angular application, which implements ControlValueAccessor
interface.
但是,我想访问与我的组件关联的FormControl
实例.我在FormBuilder
中使用反应式表单,并在formControlName
属性中提供表单控制.
However, I want to access the FormControl
instance, associated with my component. I'm using reactive forms with FormBuilder
and providing form control using formControlName
attribute.
那么,如何从自定义表单组件内部访问FormControl
实例?
SO, how do I access FormControl
instance from inside of my custom form component?
推荐答案
此解决方案源自 the Angular存储库中的讨论.请确保阅读它,如果您对此问题感兴趣,甚至最好参加.
This solution was born from the discussion in the Angular repository. Please, make sure to read it or even better to participate if you are interested in this problem.
我研究了FormControlName
指令的代码,这启发了我编写以下解决方案:
I've studied the code of FormControlName
directive and it's inspired me to write the following solution:
@Component({
selector: 'my-custom-form-component',
templateUrl: './custom-form-component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomFormComponent,
multi: true
}]
})
export class CustomFormComponent implements ControlValueAccessor, OnInit {
@Input() formControlName: string;
private control: AbstractControl;
constructor (
@Optional() @Host() @SkipSelf()
private controlContainer: ControlContainer
) {
}
ngOnInit () {
if (this.controlContainer) {
if (this.formControlName) {
this.control = this.controlContainer.control.get(this.formControlName);
} else {
console.warn('Missing FormControlName directive from host element of the component');
}
} else {
console.warn('Can\'t find parent FormGroup directive');
}
}
}
我正在将父级FormGroup
注入到组件中,然后使用通过formControlName
绑定获得的控件名称从组件中获取特定的FormControl
.
I'm injecting the parent FormGroup
to the component and then getting the specific FormControl
from it using control name obtained through formControlName
binding.
但是,请注意,此解决方案是专门针对在主机元素上使用FormControlName
指令的用例量身定制的.在其他情况下将无法使用.为此,您将需要添加一些其他逻辑.如果您认为Angular应该解决此问题,请确保访问讨论.
However, be advised, that this solution is tailored specifically for the use case where FormControlName
directive is used on host element. It won't work in other cases. For this you will need to add some additional logic. If you think, that this should be addressed by Angular, make sure to visit the discussion.
这篇关于从Angular中的自定义表单组件访问FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!