【发布时间】:2020-10-29 12:23:48
【问题描述】:
在我的 Angular 应用程序中,我有一个动态更改输入组件的表单。所有动态组件都实现了 ControlValueAccessor。
如果您在 Input 中输入值并下一个更改组件(单击按钮“将组件更改为数字”),则 ngControl 不会将其引用 valueAccessor 更改为新组件。而且我的新 Input 组件不会改变我的模型。我究竟做错了什么 ? 我在stackblitz 中有一个例子。我有一个示例代码。
我的动态表单组件:
@Component({
selector: "app-form-control-outlet",
template: ``,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FormControlOutletComponent),
multi: true
}
]
})
export class FormControlOutletComponent implements OnChanges {
@Input() component = CustomStringInputComponent;
componentRef: ComponentRef<any>;
constructor(
public injector: Injector,
private container: ViewContainerRef,
private resolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef
) {}
public ngOnChanges(changes: SimpleChanges): void {
const factory = this.resolver.resolveComponentFactory(this.component);
const componentFactory = this.resolver.resolveComponentFactory(
this.component
);
if (this.container.length > 0) {
this.container.clear();
}
this.componentRef = this.viewContainerRef.createComponent(componentFactory);
const ngControl = this.injector.get(NgControl);
ngControl.valueAccessor = this.componentRef.instance;
}
}
我的动态输入之一
@Component({
selector: "app-custom-input",
template: `
<input
[(ngModel)]="value"
(ngModelChange)="onValueChange($event)"
(blur)="onInputBlurred()"
/>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomStringInputComponent),
multi: true
}
]
})
export class CustomStringInputComponent implements ControlValueAccessor {
public value: string;
public onChange: (value: string) => void;
public onTouched: () => void;
public writeValue(value: string): void {
this.value = value;
}
public registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
}
public registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
public onValueChange(value: string): void {
this.writeValue(value);
this.onChange(value);
}
public onInputBlurred(): void {
this.onTouched();
}
}
【问题讨论】:
标签: angular typescript