Skip to content

Instantly share code, notes, and snippets.

@yjaaidi
Created April 27, 2017 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yjaaidi/5739575f34964d6d1864671954b53efb to your computer and use it in GitHub Desktop.
Save yjaaidi/5739575f34964d6d1864671954b53efb to your computer and use it in GitHub Desktop.
Angular dynamic component injector
@Injectable()
export class ComponentInjector {
constructor(
private _injector: Injector,
private _applicationRef: ApplicationRef,
private _componentFactoryResolver: ComponentFactoryResolver) {
}
injectComponent({componentClass, parentElement = null}) {
if (parentElement == null) {
parentElement = this._applicationRef.components[0].hostView['rootNodes'][0];
}
const factory = this._componentFactoryResolver.resolveComponentFactory(componentClass);
const component = factory.create(this._injector);
// if you wanna create the component as a child of ur component.
// component = this.viewContainerRef.createComponent(factory);
this._applicationRef.attachView(component.hostView);
parentElement.appendChild(component.hostView['rootNodes'][0]);
return component;
}
}
@Component({
selector: 'wt-free',
template: `
<div>HELLO {{ name }}</div>
`
})
export class DialogComponent {
@Input() name = 'Foo';
ngOnChanges(changes) {
console.log(changes);
}
}
@Component({
selector: 'wt-brain',
template: `
<div>BRAIN</div>
<button (click)="show()">SHOW</button>
<button (click)="hide()">HIDE</button>
`
})
export class BrainComponent {
private dialog: ComponentRef<DialogComponent>;
constructor(private _componentInjector: ComponentInjector) {
}
show() {
this.dialog = this._componentInjector.injectComponent({componentClass: DialogComponent}) as ComponentRef<DialogComponent>;
setInterval(() => this.dialog.instance.name += 'X', 300);
}
hide() {
this.dialog.destroy();
}
}
// <ng-container *ngComponentOutlet="cmp"></ng-container>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment