@ ViewChild 中的 read 参数是什么

需要帮助来理解以下语句中{ read: ViewContainerRef }的含义。

@ViewChild('myname', {read: ViewContainerRef}) target;
42095 次浏览

There can be several instances of various types associated with the element tag with the #myname template 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 #myname template 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.

See also How can I select an element in a component template?