How Can I Select/Access An Element In A Component Template?
A declarative way can be used instead to access elements in the view directly using elementRef. The Angular team advised against the use of ElementRef.
With that in mind: @ViewChild(), @ViewChildren(), @ContentChildren() should be our best options.
@ViewChild() supports directive or component type as parameter, or the name (string) of a template variable.
@ViewChildren() also supports a list of names as comma separated list (currently no spaces allowed @ViewChildren('var1,var2,var3')).
@ContentChild() and @ContentChildren() do the same but in the light DOM (
Descendants
@ContentChildren() is the only one that allows to also query for descendants
1 |
|
Define some element in your template with ``#`` sign.
1 |
|
Access the element from the component class using @ViewChild().
1 2 3 4 5 6 |
|