问题描述
我具有三个组件,如下图所示,并在我的功能组件中使用了自定义表单组件.但是,这两个组件之间没有直接的父子关系,并且它们之间也有表单组件.
I have three components as shown on the image below and use a custom form component in my feature component. However, there is not a direct parent-child relationship between these two components and there is also a form component between them.
我使用 @Input
属性将数据从要素传递到表单,该属性在配置数据(例如"configData")中包含输入值,然后通过 @Input将它们传递给自定义组件
属性(对于测试输入来说,我们称"configData.test")没有任何问题(初始化自定义组件时,我可以传递每个参数).但是,在初始化之后,当我设置一个在初始化时可以传递的配置值时,自定义控件不会检测到它.我还尝试将setter用于该输入,如下所示,并等待捕获 ngOnChanges
方法上的更改.我不确定如果没有直接的父子关系,是否可以更新该值,但是我避免在可重用的自定义组件中使用服务.那么,解决方案是什么?我需要BehaviourSubject并通过服务传递价值吗?
I pass data from feature to form using @Input
propert that has input values inside a config data (let's say "configData") and then pass them to custom component via @Input
property (let's say "configData.test" for test input) without any problem (I can pass every parameter when initializing the custom component). However, after initialization, when I set a config value that could be passed on initializing, it is not detected by the custom control. I also tried to use setter for that input as shown below and waited to catch the changes on ngOnChanges
method. I am not sure if it is possible to update that value if there is not a direct parent-child relationship, but I avoid to use a service in the reusable custom component. So, what is the solution? Do I have to BehaviourSubject and pass value via service?
custom-component.ts:
private _test: string;
@Input() set test(value: string) {
this._test = value;
};
get test() { return this._test; }
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
console.log(this.test);
}
这是我的组件的结构:
推荐答案
如果我正确理解,则configData是一个对象,并且仅更新其某些属性-如果是这种情况,则应注意,仅当该对象引用更改时才触发.
If I understand correctly, your configData is an object, and you only update some of its properties - if that is the case, you should be aware that angular will trigger only when that object reference is changed.
如果确实是这种情况,您可以通过以下方式之一来克服它:
If this is indeed the case here, you can overcome it in one of the following ways:
- 每当您要更改它时,
- 重新创建
configData
对象-configData = {... configData,newProp:newPropValue};
Angular会理解这是一个新对象,并且更新相关输入 - 您可以添加DoCheck生命周期挂钩-每次Angular运行更改检测时都运行-请注意,这会触发很多次
- 传递输入不可变变量,而不是可变变量-代替传递
configData
作为对象,而将属性传递给对象 - 注册一个可观察的对象,它将在每次
configData
更改时触发,然后相应地更新您的组件
- recreate the
configData
object everytime you want to change it-configData = { ...configData, newProp: newPropValue };
Angular will understand this is a new object and update relevant inputs - you can add the DoCheck lifecycle hook - this runs every time Angular runs change detection - so be mindful this will trigger a lot more times
- pass input immutable variables instead of a mutable one - instead of passing
configData
as an object, pass the properties on the object - Register with an observable which will trigger everytime
configData
changes and then update your component accordingly
这篇关于初始化组件后是否可以传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!