Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

Angular 10 async bidirectional inter component comunication

I have a ParentComponent and it contains a number of ChildComponents. The ChildComponent exposes an EventEmitter via @Output(). I use that to emit some data that is gathered from a form contained by the ChildComponent.

The ParentComponent has the means to asynchronously save the data to my backend server but the problem is, I need to somehow send back to the ChildComponent the results of the save operation so that it may close the form or show validation errors.

I'm thinking about creating some sort of Subject in my child component and emitting that together with the actual data and on the parent side I would get the emitted stuff, use the data to send to the server, and use the Subject to publish data back to the child component but it seems awfully convoluted and ugly.

If I were to use an @Input on the child component in order to receive updates for this from the ParentComponent then the parent would have to know which of the children emitted the data and that doesn't seem nice.

What nice solutions are there to ensure async bidirectional communication between parent and child components?

question from:https://stackoverflow.com/questions/65617175/angular-10-async-bidirectional-inter-component-comunication

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What I would do is that I would use Reactive Forms so parent would define whole structure of data model encoded as set of fields (groups and arrays are available as well). Then using plain reactive form API it is possible to detect changes in any part of form and get complete form value eg. for sending.

In case of backend validation errors, parent component will simpy setError or related fields of the form - children will have to be responsible for displaying/handling those errors - so it is just the same approach you want to take.

Using such approach, you will only have to pass form groups (or even single control of the form) to the child component that would be responsible for presentation of the input. No additional events are required as parent will be notified about data changes in the form out of the box trough reactive forms API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...