@angular/core#ComponentRef TypeScript Examples

The following examples show how to use @angular/core#ComponentRef. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: load-component.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Dynamically load a component from its type. The component's inputs and outputs will be initialized
     * by calling {@link #bindComponent}.
     *
     * @param options The options containing the component to load and its inputs and outputs
     * @param viewContainerRef Specifies where the loaded component should be attached. If not specified then the
     * loaded component is inserted before the application component
     * @param injector Overrides the injector to use as the parent for the component. By default this will be
     * the injector held on the `viewContainerRef`
     */
    loadComponent<T>(options: LoadComponentOptions, viewContainerRef?: ViewContainerRef, injector?: Injector): LoadedComponent {
        let componentRef: ComponentRef<T>;
        let factory = this.factories.get(options.component);
        if (!factory) {
            factory = this.componentFactoryResolver.resolveComponentFactory(options.component);
        }
        if (!viewContainerRef) {
            const appElement: Element = this.applicationRef.components[0].location.nativeElement;
            const injector1 = this.applicationRef.components[0].injector;
            componentRef = factory.create(injector1, [[appElement]]);
            this.applicationRef.attachView(componentRef.hostView);
            if (appElement.parentElement) {
                appElement.parentElement.insertBefore(componentRef.location.nativeElement, appElement.nextSibling);
            }
        }
        else {
            if (!injector) {
                injector = viewContainerRef.injector;
            }
            const index = !Utils.isEmpty(options.index) ? options.index : undefined;
            componentRef = viewContainerRef.createComponent(factory, index, injector, []);
        }
        const loadedComponent: LoadedComponent = {
            componentRef
        };
        this._bindComponent(options, loadedComponent, true);
        loadedComponent.componentRef.changeDetectorRef.detectChanges();
        return loadedComponent;
    }
Example #2
Source File: step.component.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
// 这么做完全是为了演示CDK portal的简单用法
  initComponent(ref: CdkPortalOutletAttachedRef): void {
    if (ref instanceof ComponentRef) {
      if (ref.instance instanceof StepOneComponent) {
        ref.instance.stepDirection = this.stepDirection;
        ref.instance.next.subscribe(() => {
          this.currentStep = this.currentStep + 1;
          ref.destroy();
          this.goStep(1);
        });
      }
      if (ref.instance instanceof StepTwoComponent) {
        ref.instance.previous.subscribe(() => {
          this.currentStep = this.currentStep - 1;
          ref.destroy();
          this.goStep(0);
        });
        ref.instance.next.subscribe(() => {
          this.currentStep = this.currentStep + 1;
          ref.destroy();
          this.goStep(2);
        });
      }
      if (ref.instance instanceof StepThreeComponent) {
        ref.instance.stepDirection = this.stepDirection;
        ref.instance.next.subscribe(() => {
          this.currentStep = 1;
          ref.destroy();
          this.goStep(0);
        });
      }
    }
  }
Example #3
Source File: np-popup-menubar.directive.ts    From np-ui-lib with MIT License 6 votes vote down vote up
@HostListener("click")
  show(): void {
    if (this.overlayRef.hasAttached()) {
      this._close();
      return;
    }
    const menubarPortal = new ComponentPortal(NpMenubarComponent);
    const menubarRef: ComponentRef<NpMenubarComponent> = this.overlayRef.attach(
      menubarPortal
    );
    menubarRef.instance.items = this.items;
    menubarRef.instance.styleClass = this.styleClass;
    menubarRef.instance.inputId = this.inputId;
    menubarRef.instance.onClickMenuItem = this.onClickMenuItem;
  }
Example #4
Source File: np-popover.directive.ts    From np-ui-lib with MIT License 6 votes vote down vote up
_open(): void {
    const popoverPortal = new ComponentPortal(NpPopoverComponent);
    const popoverRef: ComponentRef<NpPopoverComponent> = this.overlayRef.attach(
      popoverPortal
    );
    popoverRef.instance.header = this.header;
    popoverRef.instance.body = this.body;
    popoverRef.instance.context = this.context;
    popoverRef.instance.width = this.width;
    popoverRef.instance.styleClass = this.styleClass;
    this.onOpen.emit();
  }
Example #5
Source File: np-tooltip.directive.ts    From np-ui-lib with MIT License 6 votes vote down vote up
_show(): void {
    const tooltipPortal = new ComponentPortal(NpTooltipComponent);
    const tooltipRef: ComponentRef<NpTooltipComponent> = this.overlayRef.attach(
      tooltipPortal
    );
    tooltipRef.instance.tooltip = this.text;
    tooltipRef.instance.context = this.context;
    tooltipRef.instance.width = this.width;
    tooltipRef.instance.styleClass = this.styleClass;
  }
Example #6
Source File: base-message.ts    From alauda-ui with MIT License 6 votes vote down vote up
protected initComponentRef(config: Config): ComponentRef<Component> {
    const portalHost = new DomPortalOutlet(
      this.wrapperInstance.elementRef.nativeElement,
      this.cfr,
      this.applicationRef,
      this.injector,
    );
    const componentRef = portalHost.attachComponentPortal(
      new ComponentPortal(this.componentClass),
    );
    componentRef.instance.setConfig(config);
    return componentRef;
  }
Example #7
Source File: image-tooltip.directive.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@HostListener('mouseenter')
	show() {
		// Create tooltip portal
		const tooltipPortal = new ComponentPortal(ImageTooltipComponent);

		// Attach tooltip portal to overlay
		const tooltipRef: ComponentRef<ImageTooltipComponent> = this.overlayRef.attach(tooltipPortal);

		// Pass content to tooltip component instance
		tooltipRef.instance.imageUrl = this.imageurl;
	}
Example #8
Source File: ui.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/*private setTitle(title: string) {
        document.title = this.intlService.formatMessage(title);
    }*/

    appInit(appComponentRef: ComponentRef<any>) {
        //this.setTitle();
        //Utils.subscribe(this.intlService.events,
        //    (value) => {
        //        this.setTitle();
        //    });

        // See https://github.com/angular/angular/issues/18817
        /*this.resizeEvent.subscribe(
            (event) => {
                appComponentRef.changeDetectorRef.markForCheck();
            });*/

        // this.loadComponent({component: DirtyChecker});
    }
Example #9
Source File: panel-factory.service.ts    From ngx-colors with MIT License 6 votes vote down vote up
createPanel(
    attachTo: string | undefined,
    overlayClassName: string | undefined
  ): ComponentRef<PanelComponent> {
    if (this.componentRef != undefined) {
      this.removePanel();
    }
    const factory: ComponentFactory<PanelComponent> =
      this.resolver.resolveComponentFactory(PanelComponent);

    this.componentRef = factory.create(this.injector);
    this.applicationRef.attachView(this.componentRef.hostView);
    const domElem = (this.componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;

    this.overlay = document.createElement("div");
    this.overlay.id = "ngx-colors-overlay";
    this.overlay.classList.add("ngx-colors-overlay");
    this.overlay.classList.add(overlayClassName);
    Object.keys(OVERLAY_STYLES).forEach((attr: string) => {
      this.overlay.style[attr] = OVERLAY_STYLES[attr];
    });
    if (attachTo) {
      document.getElementById(attachTo).appendChild(this.overlay);
    } else {
      document.body.appendChild(this.overlay);
    }
    this.overlay.appendChild(domElem);

    return this.componentRef;
  }
Example #10
Source File: platform-core.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
protected linkNgComponentWithPage(
    mpComponentInstance: MiniProgramComponentInstance,
    componentRef: ComponentRef<unknown>,
    ngModuleRef: NgModuleRef<unknown>
  ) {
    mpComponentInstance.__isLink = true;
    mpComponentInstance.__ngComponentHostView = componentRef.hostView;
    mpComponentInstance.__ngComponentInstance = componentRef.instance;
    mpComponentInstance.__ngComponentInjector = componentRef.injector;
    const ngZone = componentRef.injector.get(NgZone);
    mpComponentInstance.__ngZone = ngZone;
    const { lView, id }: { lView: LView; id: number } =
      findPageLView(componentRef);
    setLViewPath(lView, [id]);
    mpComponentInstance.__completePath = [id];
    ngZone.runOutsideAngular(() => {
      const initValue = getPageRefreshContext(lView);
      mpComponentInstance.setData(initValue);
    });
    lViewLinkToMPComponentRef(mpComponentInstance, lView);
    mpComponentInstance.__lView = lView;
    mpComponentInstance.__ngDestroy = () => {
      ngModuleRef.destroy();
      componentRef.destroy();
      removePageLViewLink(id);
      cleanAll(lView);
    };
  }
Example #11
Source File: modal-container.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
insertComponentSubscription: Subscription = this.insertComponent$.asObservable()
    .pipe(take(1))
    .pipe(delay(50)) // TODO: This is a hack to avoid doing the check of the view, let's change this in the future
    .subscribe(async () => {
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.childComponent);
      const component: ComponentRef<any> = this.modalContentContainer.createComponent(componentFactory);

      if (this.childComponentInputs) {
        for (const componentInput of this.childComponentInputs) {
          component.instance[componentInput.input] = componentInput.value;
        }
      }

      this.createdComponent$.next(component);
      this.showModal$.next(true);
    });
Example #12
Source File: component-creator.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
async createOnBody<T = any>(component: Type<T>): Promise<{
    component: ComponentRef<T>;
    open: () => void;
    close: () => Promise<any>,
    destroyed$: ReplaySubject<void>
  }> {
    const componentRef = this.componentFactoryResolver
      .resolveComponentFactory(component)
      .create(this.injector);

    const responseObject = {
      destroyed$: new ReplaySubject<void>(),
      close: () => {
        return new Promise(resolve => {
          this.ngZone.run(() => {
            this.appRef.detachView(componentRef.hostView);
            componentRef.onDestroy(() => {
              responseObject.destroyed$.next();
              responseObject.destroyed$.complete();
              resolve(true);
            });
            componentRef.destroy();
          });
        });
      },
      open: () => {
        this.ngZone.run(() => {
          this.appRef.attachView(componentRef.hostView);

          const rootNode = (componentRef.hostView as EmbeddedViewRef<ApplicationRef>).rootNodes[0] as HTMLElement;

          this.renderer.appendChild(this.document.body, rootNode);
        });
      },
      component: componentRef,
    };

    return responseObject;
  }
Example #13
Source File: grid-demo.component.ts    From flingo with MIT License 5 votes vote down vote up
createComponent<T>(type: Type<T>): ComponentRef<T> {
        const componentFactory = this.componentFactory.resolveComponentFactory(type);
        return this.viewContainerRef.createComponent<T>(componentFactory);
    }
Example #14
Source File: mat-table-row.directive.ts    From flingo with MIT License 5 votes vote down vote up
rowComponentRef: ComponentRef<any>;
Example #15
Source File: mat-table-filter.directive.ts    From flingo with MIT License 5 votes vote down vote up
rowComponentRef: ComponentRef<any>;
Example #16
Source File: loading.directive.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
// Todo: In the future maybe we could make this dinamyc IE use multiple kinds of loading
  loadingComponentRef!: ComponentRef<PulseLoadingComponent>;
Example #17
Source File: load-component.directive.ts    From sba-angular with MIT License 5 votes vote down vote up
/**
     * Used to emit events when the component is created and destroyed
     */
    @Output("sqLoadComponent") eventEmitter = new EventEmitter<{componentRef: ComponentRef<Type<any>> | undefined}>();
Example #18
Source File: container-item.ts    From slate-angular with MIT License 5 votes vote down vote up
blockCardComponentRef: ComponentRef<SlateBlockCardComponent>;
Example #19
Source File: container-item.ts    From slate-angular with MIT License 5 votes vote down vote up
componentRef: ComponentRef<K>;
Example #20
Source File: component-template-hook.factory.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
export function findPageLView(componentRef: ComponentRef<unknown>) {
  const lView = findCurrentComponentLView(componentRef.instance);
  const id = lViewRegistryMap.get(lView)!;
  lViewRegistryMap.delete(lView);
  pageRegistryMap.set(id, lView);
  return { lView: lView as any, id: id };
}
Example #21
Source File: table-cell.component.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
private componentRef: ComponentRef<any>;
Example #22
Source File: notification.controller.ts    From onchat-web with Apache License 2.0 5 votes vote down vote up
private componentRef: ComponentRef<NotificationComponent>;
Example #23
Source File: factory.component.ts    From open-source with MIT License 5 votes vote down vote up
// DynControl
  private component!: ComponentRef<AbstractDynControl>;
Example #24
Source File: datetime-picker.component.ts    From angular-material-components with MIT License 5 votes vote down vote up
/** Reference to the component instantiated in popup mode. */
  private _popupComponentRef: ComponentRef<NgxMatDatetimeContent<D>> | null;
Example #25
Source File: ngx-colors-trigger.directive.ts    From ngx-colors with MIT License 5 votes vote down vote up
panelRef: ComponentRef<PanelComponent>;
Example #26
Source File: panel-factory.service.ts    From ngx-colors with MIT License 5 votes vote down vote up
componentRef: ComponentRef<PanelComponent>;
Example #27
Source File: aem-component.directive.ts    From aem-angular-editable-components with Apache License 2.0 5 votes vote down vote up
/**
   * Dynamically created component
   */
  private _component: ComponentRef<MappedComponentProperties>;
Example #28
Source File: dialog.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
    if (this.portalOutlet.hasAttached()) {
      throwDialogContentAlreadyAttachedError();
    }
    this.blurActiveElement();
    return this.portalOutlet.attachComponentPortal(portal);
  }
Example #29
Source File: drawer.service.ts    From alauda-ui with MIT License 5 votes vote down vote up
private drawerRef: ComponentRef<DrawerComponent>;