gpt4 book ai didi

javascript - Angular ControlValueAccessor 的默认值因内部原因而变脏

转载 作者:行者123 更新时间:2023-11-28 03:14:17 26 4
gpt4 key购买 nike

我有一个为模板驱动表单构建动态输入组件的指令。默认值由输入组件本身设置。

问题是设置默认值会导致表单被标记为脏。

如何在指令内部设置默认值而不将表单标记为脏?

@Directive({
selector: '[myFormInputFactory]',
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyFormFactoryDirective), multi: true }
]
})
export class MyFormFactoryDirective implements OnChanges, OnDestroy, ControlValueAccessor {
@Input() myFormInputFactory: DialogItem;

private componentRef: any;
private value: any;
private valueSubscription: Subscription;
private disabled = false;

constructor(
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
private _renderer: Renderer,
private _elementRef: ElementRef
) { }

onChange = (_: any) => { };
onTouched = () => { };

registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }


ngOnChanges(changes: SimpleChanges) {
if ('myFormInputFactory' in changes) {
const config = changes['myFormInputFactory'].currentValue as IConfigItem;

const factories = Array.from(this.componentFactoryResolver['_factories'].values());
const comp = factories.find((x: any) => x.selector === config.selector) as ComponentFactory<{}>;
const componentRef = this.viewContainerRef.createComponent(comp);

if (this.componentRef) {
this.componentRef.destroy();
}
this.componentRef = componentRef;
this.valueSubscription = this.componentRef._component.valueChange.subscribe(value => {
this.value = value;
this.onChange(this.value);
});
}
}

ngOnDestroy() {
if (this.valueSubscription) {
this.valueSubscription.unsubscribe();
}
}

writeValue(value: string): void {
if (this.value !== null) {
this.onChange(this.value);
}
if (value !== undefined && value !== null) {
this.value = value;
}
}
}

更新

我创建了一个StackBlitz

最佳答案

您可以创建 StackBlitz 帖子以更好地进行调试吗?

我认为部分问题可能是访问输入而不是访问 FormControl 本身。直接访问输入本身会触发 onChange 事件并将输入标记为脏,在我看来,这可能是一个问题。

您如何使用该指令?是否可以执行以下操作?

  1. 在父组件中创建FormGroup
  2. 使用 myFormInputFactory 指令时,将适当的 FormControl 引用传递给指令并将值分配给控件本身:

    this.formgroup.setValue({ 核心值(value)},{emitEvent: false})

关于javascript - Angular ControlValueAccessor 的默认值因内部原因而变脏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59786698/

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