gpt4 book ai didi

forms - Angular 动态表单可观察属性绑定(bind)

转载 作者:太空狗 更新时间:2023-10-29 19:28:45 25 4
gpt4 key购买 nike

我对一些动态生成的表单和向它们传递值有疑问。我觉得一定有人解决了这个问题,或者我遗漏了一些明显的东西,但我找不到任何提及。

例如,我有三个组件,一个父组件,一个子组件,然后是那个子组件的一个子组件。对于名称,我将使用 formComponent、questionComponent、textBoxComponent。两个 child 都在使用 changeDetection.OnPush。

因此,表单组件通过输入将一些值向下传递给 questionComponent,并且一些组件使用异步管道在商店中订阅它们各自的值。

QuestionComponent 动态创建不同的组件,如果它们匹配,则将它们放在页面上(这么多类型的组件,但每个 questionComponent 只处理一个组件。

一些代码:

@Input() normalValue
@Input() asyncPipedValue
@ViewChild('questionRef', {read: ViewContainerRef}) public questionRef: any;
private textBoxComponent: ComponentFactory<TextBoxComponent>;

ngOnInit() {
let component =
this.questionRef.createComponent(this.checkboxComponent);
component.instance.normalValue = this.normalValue;
component.instance. asyncPipedValue = this. asyncPipedValue;
}

这适用于所有 normalValues 实例,但不适用于 asyncValues。我可以在 questionComponent 的 ngOnChanges 中确认该值正在更新,但该值未传递给 textBoxComponent。

我基本上需要的是异步管道,但不是模板。我尝试了多种解决方案以不同的方式传递 asyncValues,我尝试检测 asyncPipeValue 何时更改,并在 textBoxComponent 上触发 changeDetectionRef.markForChanges() ,但这仅在我将 changeDetectionStrategy 更改为正常时有效,这有点破坏性能我从使用 ngrx 中获得的 yield 。

这似乎是一个太大的疏忽,以至于还没有解决方案,所以我假设只是我没有想到什么。有什么想法吗?

最佳答案

我做了类似的事情,我用来 self 的 Ngrx 商店的数据填充了表单。我的表单不是动态的,所以我不能 100% 确定这是否也适用于您。

仅使用 setter 定义您的输入,然后在您的表单/表单控件上调用 patchValue() 或 setValue()。您的根组件保持不变,使用异步管道将数据传递到您的下一个组件。

@Input() set asyncPipedValue(data) {
if (data) {
this.textBoxComponent.patchValue(data);
}
}

patchValue() 在 AbstractControl 类上。如果您无法从您的问题组件访问它,您的 TextBoxComponent 可能会公开一个类似的方法,可以从您的 QuestionComponent 调用该方法,实现执行控件的更新。

不过要注意一件事,如果您还在表单/控件上订阅 valueChanges,您可能需要设置第二个参数,这样 valueChanges 事件就不会立即触发。

this.textBoxComponent.patchValue(data, { emitEvent: false });

this.textBoxComponent.setValue(...same as above);

然后在你的 TextBoxComponent 中

this.myTextBox.valueChanges
.debounceTime(a couple of seconds maybe)
.distinctUntilChanged()
.map(changes => {
this.store.dispatch(changes);
})
.subscribe();

这种方法非常有效,并且无需在任何地方设置保存/更新按钮。

关于forms - Angular 动态表单可观察属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44829077/

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