我遇到了同样的问题。奇怪的是没有更多关于此的 Stackoverflow 帖子。上面的答案对我不起作用,但这就是我在有更多的情况下解决它的方法。
@Directive({
selector: '[hybridFormControl]'
})
class HybridFormControl Directive extends FormControlName implements ControlValueAccessor, OnChanges {
@Input('hybridFormControl') name: string;
onChange;
onTouched;
constructor(
@Optional() protected formGroupDirective: FormGroupDirective,
@Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
private fb: FormBuilder,
private renderer: Renderer2,
private element: ElementRef
) {
super(formGroupDirective, [], [], valueAccessors, null);
this.valueAccessor = this;
}
ngOnChanges(changes: SimpleChanges): void {
if (!this._registered) {
// dynamically create the form control model on the form group model.
this.formGroup = this.formGroupDirective.form;
this.formGroup.registerControl(name, this.fb.control(''));
this._registered = true;
}
// IMPORTANT - this ties your extended form control to the form control
// model on the form group model that we just created above. Take a look
// at Angular github source code.
super.ngOnChanges(changes);
}
@HostListener('input', ['$event.target.value'])
@HostListener('change', ['$event.target.value'])
onInput(value): void {
this.onChange(modelValue);
}
writeValue(value): void {
const element = this.element.nativeElement;
this.renderer.setProperty(element, 'value', value);
}
registerOnChange(fn): void {
this.onChange = fn;
}
registerOnTouched(fn): void {
this.onTouched = fn;
}
}
这个混合组件可以像这样使用:
@Component({
selector: 'app',
template: `
<form formGroup=[formGroup]>
<input type="text" hybridFormControl="myName">
</form>
`
class AppComponent {
formGroup: FormGroup
constructor(fb: FormBuilder) {
this.form = this.fb.group({});
}
}
资料来源:https ://github.com/angular/angular/blob/master/packages/forms/src/directives/reactive_directives/form_control_name.ts#L212