Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $
and $$
.
I was just wondering how to go about it in Angular.
Take the example from the tutorial:
import {Component} from '@angular/core';
@Component({
selector:'display',
template:`
<input #myname (input)="updateName(myname.value)"/>
<p>My name : {{myName}}</p>
`
})
export class DisplayComponent {
myName: string = "Aman";
updateName(input: String) {
this.myName = input;
}
}
How do I catch hold or get a reference of the p
or input
element from within the class definition?
Best Answer
Instead of injecting
ElementRef
and usingquerySelector
or similar from there, a declarative way can be used instead to access elements in the view directly:element
StackBlitz example
@ViewChildren('var1,var2,var3')
).<ng-content>
projected elements).descendants
@ContentChildren()
is the only one that allows to also query for descendants{descendants: true}
should be the default but is not in 2.0.0 final and it's considered a bugThis was fixed in 2.0.1
read
If there are a component and directives the
read
parameter allows to specify which instance should be returned.For example
ViewContainerRef
that is required by dynamically created components instead of the defaultElementRef
subscribe changes
Even though view children are only set when
ngAfterViewInit()
is called and content children are only set whenngAfterContentInit()
is called, if you want to subscribe to changes of the query result, it should be done inngOnInit()
https://github.com/angular/angular/issues/9689#issuecomment-229247134
direct DOM access
can only query DOM elements, but not components or directive instances:
get arbitrary projected content
See Access transcluded content