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 (projected elements).

Descendants

@ContentChildren()  is the only one that allows to also query for descendants

1
@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField; 

Define some element in your template with ``#`` sign.

1
<input #myname>

Access the element from the component class using @ViewChild().

1
2
3
4
5
6
@ViewChild('myname') input; 
element

ngAfterViewInit() {
 console.log(this.input.nativeElement.value);
}

Related Posts

0 Comments

12345

    00