Angular Query黑魔法

Query一个Directive,拿到这个Directive的host Element:


更进一步地,通过Query,可以从指定的Element的Injector(View Injector)中获取你想要的服务:

在这个例子中,我们想要query的服务就是Component实例。

定义一个抽象类(而不是interface,因为运行时没有interface,不能作为DI token)。这个抽象类将Component类与query使用者解耦,使用query的时候不需要知道Component的类型,而是通过这个抽象类的API与Component进行交互。

让我们想要query的component实现这个抽象类。当然,我们还要在相应的View Injector中Provide这个服务:

解决Typescript报错:

https://youtu.be/EoSn8qASqQA?...

评论

暂无评论