Reyan Tropia
Reyan Tropia

Reputation: 140

Using Component without Import

Hi I would like to know if its possible to use a component without importing it again if it's already declared in AppModule. Since I have 10 or more pages/component to use and it will be difficult to import each one and track.

Here is my app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

@NgModule({
declarations: [
    MyApp,
    HomePage
],
imports: [
    IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
    MyApp,
    HomePage
],
providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}

And I would like to use HomePage without re-importing it. Since I have so many pages to deal it.

other-page.ts

import { Component } from '@angular/core';
@Component({
  selector: 'page-home',
  templateUrl: 'login.html',
  providers: [LoginService]
})
export class LoginPage {
constructor(){ }
//Call HomePage here without having to import it again.
}

Upvotes: 2

Views: 3332

Answers (2)

Robert P
Robert P

Reputation: 9793

To use the Comonent in your source code (ts-file), you need to import it, so that TypeScript recognizes it.
If you only want to use it in the Template, it needs to be recognized only by the Angular framework and no import is needed.

To let Angular know about your Component, you need to declare it in a NgModule. Every Component inside this NgModule will then know your Component.
To let other NgModules know your Component, you need to export it from the declaring NgModule and import that NgModule in the other NgModules.

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

If you mention a class somewhere in code, it has to be imported, otherwise it's not recognized as that class which makes the code invalid or at least not do what you expect.

The imports at the top of the file are not related to Angular at all, they are TypeScript imports. The imports in @NgModule() are Angular imports and fullfill an entirely different purpose than TS imports.

Therefore adding components to @NgModule() doesn't make other imports obsolete.

Upvotes: 3

Related Questions