0

If I use import { Renderer2 } from '@angular/core'; in my shared.module in angular 4, why can't I also add it in the import array such as:

@NgModule({
    imports: [
        Renderer2,
  ...
 ]

Adding it in the import gives an error. Here is why I need Renderer2:

myComponent.html (part of my shared.module):

<input #searchElem type="text">

myComponent.ts

 constructor(private renderer: Renderer2) {
    }

const element = this.renderer.selectRootElement('#searchElem');
setTimeout(() => element.focus(), 0);

This is done to be able to set the focus of an element.

2
  • Renderer2 is supported by angular5. please use Renderer for the angular 4 Commented Mar 21, 2018 at 11:46
  • According to the docs, Renderer2 already existed in v4. Commented Mar 21, 2018 at 11:53

2 Answers 2

2

Renderer2 is an injectable (service) part of Angular core. It's not a module. The import property in @NgModule is to import other modules. You should be able to use Renderer2 in your component the way you have it, but simply remove it from the module imports.

Sign up to request clarification or add additional context in comments.

5 Comments

Ok Sam, thank you. Any thoughts on why I get The selector "#searchElem" did not match any elements? I do have #searchElem in the html
Ah, if you need to get a reference to an element in the template of a component, you don't need Renderer2. Use ViewChild instead.
Ex: @ViewChild('searchElem') searchElem: ElementRef
Yes, actually that's what I am using. I have @ViewChild('searchElem') : ElementRef and then if I dothis.searchElem.nativeElement as HTMLInputElement).focus(); , nativeElement can be problematic and cause errors, hence why I was trying my luck with Renderer
Oh are you attempting to access the searchElement property in the constructor? Since Angular has to query the element first, the earliest you can access it is in the ngOnInit lifecycle hook. Here is a simple example.
0
imports

imports describe which dependencies this module has. If your module depends on other modules, you list them here. example

 imports: [
    BrowserModule, HttpClientModule,DataTableModule, AppRoutingModule,
  ],

The short answer is that you put something in your NgModule’s imports if you’re going to be using it in your templates or with dependency injection.

import statement is used to import other typescript files and class

import {className} from 'filePath';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.