Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the read parameter in @ViewChild for

Tags:

angular

Need help to understand meaning of {read: ViewContainerRef} in following statement.

@ViewChild('myname', {read: ViewContainerRef}) target; 
like image 333
Pankaj Kapare Avatar asked May 26 '16 02:05

Pankaj Kapare


People also ask

What is read in ViewChild?

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.

What does @ViewChild do in Angular?

The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.

What does ViewChild return?

ViewChild returns the first matching element and ViewChildren returns all the matching elements as a QueryList of items. We can use these references to manipulate element properties in the component.


1 Answers

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?

like image 109
Günter Zöchbauer Avatar answered Oct 05 '22 14:10

Günter Zöchbauer