Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to select an element in a component template?

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?
by

2 Answers

MounikaDasa
Instead of injecting ElementRef and using querySelector or similar from there, a declarative way can be used instead to access elements in the view directly:

<input #myname>
@ViewChild('myname') input;
element

ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
pankajshivnani123
import { Component, ElementRef, OnInit } from '@angular/core';

@Component({
selector:'display',
template:`
<input (input)="updateName($event.target.value)">
<p> My name : {{ myName }}</p>
`
})
class DisplayComponent implements OnInit {
constructor(public element: ElementRef) {
this.element.nativeElement // <- your direct element reference
}
ngOnInit() {
var el = this.element.nativeElement;
console.log(el);
}
updateName(value) {
// ...
}
}

Login / Signup to Answer the Question.