简体   繁体   English

Angular2 - 来自TypeScript基础抽象类的@ViewChild

[英]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? 我正在寻找@ 这个SO Q&A ,并想知道是否有可能有一个基础abstract class 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 ? 而不是一个interface ,是有可能有在那些经由父组件访问的子组件的基类的不同的实现@ViewChildAngular2装饰?

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? 理想情况下,我希望有一种方法可以通过父Router实例化的子组件能够调用父路由器 - 这有意义吗? I want the child to be able to call parentRouter.navigate(["SomeOtherRoute", { args: 'blah' }]); 我希望孩子能够调用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. 我最初的方法是让子组件实现一个基类,父组件将通过@ViewChild装饰器获得引用。 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). 父级将subscribe试图调用导航事件的子操作,并且其处理程序将调用router.navigate (因为它具有父级别的路由器)。

It is actually quite simple. 它实际上非常简单。 For instance, if you have a class EmployeeComponent that extends PersonComponent which is an abstract class. 例如,如果您有一个EmployeeComponent类,它扩展了PersonComponent,它是一个抽象类。

You can make it approachable by adding this in the EmployeeComponent: 您可以通过在EmployeeComponent中添加它来使其平易近人:

providers: [ {provide: PersonComponent, useExisting: EmployeeComponent }]

And use ViewChildren() or ContentChildren() in your container component like this: 并在容器组件中使用ViewChildren()或ContentChildren(),如下所示:

@ViewChildren(PersonComponent) public persons: QueryList<PersonComponent>;

You can't use @ViewChildren() or any of the similar decorators to query for subclasses of components. 您不能使用@ViewChildren()或任何类似的装饰器来查询组件的子类。

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 https://stackoverflow.com/a/41151492/4293638

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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