Angular 2 (variable to element reference)

980 views
Skip to first unread message

Micael Pedrosa

unread,
Aug 14, 2015, 12:21:16 PM8/14/15
to AngularJS
Is there any way to attach a element reference to a component variable? Like: 
  <h1 #header > Message Header </h1>
and then attach the h1 element ref like for example (annotate a variable):
  @ElementRef header;

Eric Martinez

unread,
Aug 14, 2015, 1:18:31 PM8/14/15
to AngularJS
Hey Michael, I'm not sure if I understood you correctly. Having the reference in #header you should be able to pass the raw element to any Componnet/Directive

Say something like this

// HTML

<h1 #header > Message Header </h1>

<my-cmp [header]="header"></my-cmp>


// Component
@Component({
   selector
: 'my-cmp',
   properties
: ['header: header']
});
@View({
   
...
});
class MyCmp {
   constructor
() {
       console
.log(this.header); // I think it won't be printed at this point
   
}


   onInit
() {
      console
.log(this.header); // At this point it should be printable
   
}  
}

Pete Moss

unread,
Aug 14, 2015, 1:21:07 PM8/14/15
to AngularJS
Micael,

Not sure what you are trying to do. Do you want to reference the DOM element in the controller code? If so, I have had success using jQuery and using the ElementRef that you can have access to in the constructor. For example, if the template includes 
<h1 id="header">Message Header</h1>
and your component constructor looks like:
constructor(elemRef: ElementRef)
{
  var el = $("#header", elemRef.nativeElement);
  ...
}

Don't know if that is what you are looking for.

I believe the local variable hash notation is useful only for referencing the element in the template.

Micael Pedrosa

unread,
Aug 14, 2015, 1:43:40 PM8/14/15
to AngularJS
Yes, something like that.
Reply all
Reply to author
Forward
0 new messages