I was looking @ this SO Q & A, and wondering if it was possible to have a base abstract class
instead? Rather than an interface
, is it possible to have differing implementations of a base class in child components that are accessible to the parent component via the @ViewChild
decorator in Angular2?
Ideally, I would like to have a means for child components that are instantiated via a parent Router
to be capable of invoking the parent router -- does that make sense? I want the child to be able to call parentRouter.navigate(["SomeOtherRoute", { args: 'blah' }]);
.
My initial approach was to have the child components implement a base class that the parent component would get a reference to via the @ViewChild
decorator. The parent would subscribe
to the action of the child attempting to invoke a navigation event, and its handler would invoke the router.navigate
(since it has the router at the parent level).
It is actually quite simple. For instance, if you have a class EmployeeComponent that extends PersonComponent which is an abstract class.
You can make it approachable by adding this in the EmployeeComponent:
providers: [ {provide: PersonComponent, useExisting: EmployeeComponent }]
And use ViewChildren() or ContentChildren() in your container component like this:
@ViewChildren(PersonComponent) public persons: QueryList<PersonComponent>;
Yes! It is possible, and I find it can be cleaner in some cases, although for your use case I think a service is preferrable. See my answer to the original question about interfaces. I maybe should have posted it here.
https://stackoverflow.com/a/41151492/4293638
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With