问题
I am having some queries regarding component interaction in angular6.For component interaction we are having methods like @Input, @Output, viewChild and services. But most of the cases we will use services.
At what situation we need to use @Input, @Output and viewChild for passing values in our application
@Input, @Output and viewChild method having any limitations?
Can we pass large amount of data or array of values Using @Input, @Output method.
Can we use @Input and @Output within local scope? Please help me to clarify my doubts
回答1:
@Input - From the Docs
The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property's value.
This approach is useful when your Components having Parent and Child relation. This is simple approach to pass the data from Parent to Child.
As from the docs we don't need to change the data when Parent variable gets updated, that means no need to bother about the Synchronization until the object reference doesn't change.
@Output - From the Docs
The DOM property bound to the output property is automatically updated during change detection.
This is approach is useful when you want inform Parent Component about some action is done in Child Component.
You can also pass the data from Child Component to Parent Component but the actual use-case is change detection. When you want perform some operation in the Parent Component depending on Child Component actions.
@ViewChild - From the Docs
Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is update.
It is useful when you want to access more than one property from Child Component and In Angular we can define plain HTML elements in component template by combining which can accessed with ViewChild.
If you want use more Child Properties for doing the operations in Parent Component then it is useful.
Sevices -- From the Docs
Services are a great way to share information among classes that don't know each other.
As Stated in the docs these classes are useful when you want share the data across multiple components and There is no need to to be relation between them.
Services can depend on other services and by using an external service you are centralizing data into one external object that is responsible to manage and update data.
With help of latest RxJS Libary you can centralize data in efficient way (for limited pint of time) with help of Subject and Behavior Subject.
来源:https://stackoverflow.com/questions/57107741/for-component-interaction-which-method-is-best-input-output-or-using-service