@ViewChild(‘myname’, {read: ViewContainerRef}) target : ViewContainerRef;

@ViewChild(‘myname’, {read: ViewContainerRef}) target : ViewContainerRef;

所支持的选择器包括:

  • 任何带有 @Component 或 @Directive 装饰器的类
  • 字符串形式的模板引用变量(比如可以使用 @ViewChild('cmp') 来查询 <my-component #cmp></my-component>
  • 组件树中任何当前组件的子组件所定义的提供商(比如 @ViewChild(SomeService) someService: SomeService )
  • 任何通过字符串令牌定义的提供商(比如 @ViewChild('someToken') someTokenVal: any )
  • TemplateRef(比如可以用 @ViewChild(TemplateRef) template; 来查询 <ng-template></ng-template>

@ViewChild(‘myname’, {read: ViewContainerRef}) target : ViewContainerRef;

The following is an explanation to read:

There can be several instances of various types associated with the element tag with the #mynametemplate variable.

For each element there is an ElementRef and ViewContainerRef (maybe others from components or directives applied to that tag).

If the element is a component, then there is the component instance.

There can also be one or several directives applied to the element

With {read: SomeType} you tell what type should be returned from the element with the #mynametemplate variable.

If you don’t provide the read parameter, @ViewChild() returns the

  • ElementRef instance if there is no component applied, or the
  • component instance if there is.
  • If you want to get something different you need to explicitly specify using read.

元数据属性

  • selector – 用于查询的指令类型或名字。selector – the directive type or the name used for querying.
  • read – 从查询到的元素中读取另一个令牌。read – read a different token from the queried elements.
  • static – whether or not to resolve query results before change detection runs (i.e. return static results only). If this option is not provided, the compiler will fall back to its default behavior, which is to use query results to determine the timing of query resolution. If any query results are inside a nested view (e.g. *ngIf), the query will be resolved after change detection runs. Otherwise, it will be resolved before change detection runs.
  • @ViewChildren() also supports a list of names as comma separated list (currently no spaces allowed @ViewChildren('var1,var2,var3')).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.