ng-dynamic-component-loader
v1.0.2
Published
A simple service that will dynamically add a component to the DOM at run time. Depending on the location provided, you can attach a component to a ViewContainer, an HTML element, or the root of the application. This makes it very easy to add components su
Downloads
17
Readme
NgDynamicComponentLoader
A simple service that will dynamically add a component to the DOM at run time. Depending on the location provided, you can attach a component to a ViewContainer, an HTML element, or the root of the application. This makes it very easy to add components such as notifications, alerts or modals anywhere in the DOM.
Install
npm i --save ng-dynamic-component-loader
Usage
For dynamic components, they need to be added to the entryComponents of your module that they will be used in.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { DynamicComponentComponent } from './dynamic-component/dynamic-component.component';
@NgModule({
declarations: [
AppComponent,
DynamicComponentComponent
],
entryComponents: [DynamicComponentComponent],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Then in your parent component
import { Component } from '@angular/core';
import { NgDynamicComponentLoader } from 'ng-dynamic-component-loader';
import { DynamicComponentComponent } from './dynamic-component/dynamic-component.component';
@Component({
selector: 'app-root',
template: `
<button (click)="addComponent()">Add Dynamic Component</button>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private loader: NgDynamicComponentLoader) {}
addComponent() {
// if no location is passed, then the component will be
// attached to the root element of the application
this.loader.attachComponent(DynamicComponentComponent)
}
}
API
public attachComponent(component: any, location?: HTMLElement|ViewContainerRef): ComponentRef<any>