问题
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.
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);
}
Here is the structure of my components:
回答1:
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:
- 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
来源:https://stackoverflow.com/questions/65228555/is-it-possible-to-pass-data-after-initializing-the-components