Angular2 - Unhandled Promise rejection: No provider for ElementRef

3,044 views
Skip to first unread message

Paul Belowee

unread,
Apr 15, 2016, 5:10:02 AM4/15/16
to AngularJS
I'm want to get reference to dom node of a component.
Here is the code:

import {Component, Inject, ElementRef} from 'angular2/core';

declare var ol: any;


@Component({

  selector: 'olmap'

})


export class MapComponent {

  elementRef: ElementRef;


  constructor(@Inject(ElementRef) elementRef: ElementRef){

   this.elementRef = elementRef;

  }

}


Compiling - ok.
and runtime error:  Unhandled Promise rejection: No provider for ElementRef

What is wrong?


Günter Zöchbauer

unread,
Apr 16, 2016, 12:49:43 PM4/16/16
to AngularJS
I don't see anything wrong. 
You can shorten the constructor to

 constructor(private elementRef: ElementRef){} 


(or `public` instead of `private`)

Your problem is outside of the code your provided.

Does your component not have a `template` or is this just because you shortened the code before posting?

Paul Belowee

unread,
Apr 18, 2016, 9:31:01 AM4/18/16
to AngularJS

Forgot bindings:


import {Component, Inject, ElementRef} from 'angular2/core';

declare var ol: any;


@Component({

  selector: 'olmap',

  bindings: [ElementRef]

Günter Zöchbauer

unread,
Apr 20, 2016, 3:09:23 AM4/20/16
to AngularJS
adding `ElementRef` to `bindings` isn't necessary. 

There is something else wrong in your application.

Some other hints:

`bindings` is deprecated in favor of `providers`

`@Inject(ElementRef)` is redundant if the parameter has a type annotation with the same type.

Also this constructor does the same as yours while being much shorter

constructor(public elementRef: ElementRef){}

Reply all
Reply to author
Forward
0 new messages