Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 -- @ViewChild from TypeScript base abstract class

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).

like image 446
David Pine Avatar asked Apr 25 '16 13:04

David Pine


2 Answers

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>;

like image 55
NiZa Avatar answered Oct 28 '22 07:10

NiZa


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

like image 35
Kyle Zimmer Avatar answered Oct 28 '22 05:10

Kyle Zimmer