如果我想获得对Component中投影的所有元素的引用,我该怎么办?
假设我有AppComponent将一些链接和图像投影到TestComponent中:
@Component({ selector: 'test',template: '<ng-content></ng-content>' }) class TestComponent {} @Component({ selector: 'app',template: ` <test> <img src="http://example.org/1.jpg"> <a href="http://example.org">Some Link</a> </test> `,directives: [ TestComponent ] }) export class AppComponent {}
现在,我如何在TestComponent中获得对这些链接和图像(以及可能的其他元素类型)的引用?
阅读this post建议如下:
Solution: ContentChildren + directive with li selector
One great solution is to take advantage of the selector in the
@Directive decorator. You simply define a directive that selects for
<li> elements,then use a @ContentChildren query to filter all <li>
elements down to only those that are content children of the
component.
但是这只有在我想获得单个元素类型时才有效,但是如果我想获得多个类型,这意味着我必须为我想要的每种类型创建一个指令(如果我想要所有类型,那该怎么办?)……这不是一种实用的方法.