I have written an angular 2 component:
@Component({
templateUrl: ',
selector: 'dino',
templateUrl: './dino.component.html',
styleUrls: ['./dino.component.css']
})
export class DinoComponent {
...
}
It is an image viewer contained in a modal window.
I want to share this component in different part of my app like a service.
If I use the selector in different part of my app it will create many instances of the component waisting memory, correct?
The viewer should be loaded only once and just the images should change according to different urls accessible with buttons scattered all over my app.
I know I can create a service that load images as requested but how do I use the modal with template as service so that the common parts like menus, frame, etc are loaded only once? Can a service have a html template associate with it?
How do I ensure the modal viewer is a singleton shared by the whole app?
Thank you for your help.
Create a module for your component and service like this:
@NgModule({
imports: [
CommonModule
],
declarations: [YourComponent],
exports: [YourComponent]
})
export class TranslationModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: YourModule,
providers: [
YourService
]
};
}
}
In your app.module
import the module as YourModule.forRoot()
in all other module import it as YourModule
. Keep your images within the service.
This way your service is a singleton. It doesn't matter if your component tag is used multiple times. They are not rendered if they are not displayed.