What is the read parameter in @ViewChild for
Asked Answered
B

1

116

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

@ViewChild('myname', {read: ViewContainerRef}) target;
Bastia answered 26/5, 2016 at 2:58 Comment(1)
see thisObrien
A
156

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?

Ajit answered 27/5, 2016 at 6:22 Comment(9)
'maybe others from components or directives applied to that tag' : How can we get the full list of possible type ?Campaign
The directives and components listed in directives: [...] of the current component or in PLATFORM_DITECTIVES where a selectors matches. You can use #35234072 to investigate on a running application.Calvary
Ho so it's only one of ElementRef, ViewContainerRef or Directive, with components and directives defined by user just being sub-types of Directive ? I was thinking about other types, not sub-types defined by user like directives. For instance injecting directly the HTMLElement instead of the ElementRef.Campaign
This only supports Angular types that are associated with a node. HTMLElement is not one of them. ElementRef allows to access the HTMLElement using `ElementRef.nativeElement.Calvary
You are awesome. How did you figure this out?Elamitic
Just trying all kind of things and investigating the Angular2 source.Calvary
How can I get what i want, when I pass element to the function on that element? eg: <component #myElem (click)="someMethod(#myElem)">. How to get ElementRef in that method instead of component?Container
You can't when the element is a component. You can only specify what you want if you use @ViewChild(... read: ElementRef) ...Calvary
Just wondering. If I do it like @ViewChild('form', {static: false}) public form: NgForm; is angular also reading the type hint like the injector does? Or not? and is it faster to always add the read option? or is it actually slower?Danielldaniella

© 2022 - 2024 — McMap. All rights reserved.