gpt4 book ai didi

angular - 更改 ngControl.valueAccessor 以动态更改组件

转载 作者:行者123 更新时间:2023-12-04 15:14:24 26 4
gpt4 key购买 nike

在我的 Angular 应用程序中,我有一个动态更改输入组件的表单。所有动态组件都是 ControlValueAccessor 的实现。

如果您在 Input 中输入值,然后更改组件(单击“将组件更改为数字”按钮),则 ngControl 不会将其引用 valueAccessor 更改为新组件。我的新输入组件不会改变我的模型。我究竟做错了什么 ?我在 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();
}
}

最佳答案

发生这种情况是因为当您更改 valueAccessor 时,Angular 不会再次在该新组件上注册 onChange 和 onTouched 事件。

作为解决方法,您可以尝试手动注册这些事件:

const ngControl = this.injector.get(NgControl);
const valueAccessor = ngControl.valueAccessor as any;
if (valueAccessor && valueAccessor.onChange) {
this.componentRef.instance.registerOnChange(valueAccessor.onChange);
this.componentRef.instance.registerOnTouched(valueAccessor.onTouched);
}
ngControl.valueAccessor = this.componentRef.instance;

Forked Stackblitz

关于angular - 更改 ngControl.valueAccessor 以动态更改组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64591056/

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