简体   繁体   中英

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

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

You can't use @ViewChildren() or any of the similar decorators to query for subclasses of components.

Only names of template variables and concrete component and directive types (the types that are actually instantiated as component in your view) are supported.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM