Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @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>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement