@angular/core#ApplicationRef TypeScript Examples

The following examples show how to use @angular/core#ApplicationRef. 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: error-handler.service.ts    From matx-angular with MIT License 6 votes vote down vote up
// https://github.com/angular/angular/issues/17010
    handleError(error: any) {
        let increment = 5;
        let max = 50;

        // Prevents change detection
        let debugCtx = error['ngDebugContext'];
        let changeDetectorRef = debugCtx && debugCtx.injector.get(ChangeDetectorRef);
        if (changeDetectorRef) changeDetectorRef.detach();

        this.errorCount = this.errorCount + 1;
        if (this.errorCount % increment === 0) {
            console.log(' ');
            console.log(`errorHandler() was called ${this.errorCount} times.`);
            console.log(' ');
            super.handleError(error);

            if (this.errorCount === max) {
                console.log(' ');
                console.log(`Preventing recursive error after ${this.errorCount} recursive errors.`);
                console.log(' ');

                let appRef = this.injector.get(ApplicationRef);
                appRef.tick();
            }
        }
        else if (this.errorCount === 1) {
            super.handleError(error);
        }
    }
Example #2
Source File: dialog.service.ts    From mysteryofthreebots with Apache License 2.0 6 votes vote down vote up
constructor(
    rendererFactory: RendererFactory2,
    private readonly resolver: ComponentFactoryResolver,
    private readonly injector: Injector,
    private readonly appRef: ApplicationRef,
    @Inject(DOCUMENT) private readonly document: HTMLDocument
  ) {
    this.renderer = rendererFactory.createRenderer(null, null);
    this.handleCloseDialog = this.handleCloseDialog.bind(this);
  }
Example #3
Source File: golden-layout-host.component.ts    From golden-layout-ng-app with MIT License 6 votes vote down vote up
constructor(private _appRef: ApplicationRef,
    private _elRef: ElementRef<HTMLElement>,
    private goldenLayoutComponentService: GoldenLayoutComponentService,
  ) {
    this._goldenLayoutElement = this._elRef.nativeElement;

    this.goldenLayoutComponentService.registerComponentType(ColorComponent.componentTypeName, ColorComponent);
    this.goldenLayoutComponentService.registerComponentType(TextComponent.componentTypeName, TextComponent);
    this.goldenLayoutComponentService.registerComponentType(BooleanComponent.componentTypeName, BooleanComponent);
  }
Example #4
Source File: hmr.ts    From angular-material-admin with MIT License 6 votes vote down vote up
hmrBootstrap = (module: any, bootstrap: () => Promise<NgModuleRef<any>>) => {
  let ngModule: NgModuleRef<any>;
  module.hot.accept();
  bootstrap().then(mod => ngModule = mod);
  module.hot.dispose(() => {
    const appRef: ApplicationRef = ngModule.injector.get(ApplicationRef);
    const elements = appRef.components.map(c => c.location.nativeElement);
    const makeVisible = createNewHosts(elements);
    ngModule.destroy();
    makeVisible();
  });
}
Example #5
Source File: hmr.ts    From youpez-admin with MIT License 6 votes vote down vote up
hmrBootstrap = (module: any, bootstrap: () => Promise<NgModuleRef<any>>) => {
  let ngModule: NgModuleRef<any>
  module.hot.accept()
  bootstrap().then(mod => ngModule = mod)
  module.hot.dispose(() => {
    const appRef: ApplicationRef = ngModule.injector.get(ApplicationRef)
    const elements = appRef.components.map(c => c.location.nativeElement)
    const makeVisible = createNewHosts(elements)
    ngModule.destroy()
    makeVisible()
  })
}
Example #6
Source File: notification.service.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    overlay: Overlay,
    injector: Injector,
    applicationRef: ApplicationRef,
    cfr: ComponentFactoryResolver,
    @Optional()
    @Inject(NOTIFICATION_CONFIG)
    globalConfig: NotificationGlobalConfig,
  ) {
    super(
      overlay,
      injector,
      applicationRef,
      cfr,
      'aui-notification-overlay-pane',
      NotificationWrapperComponent,
      NotificationComponent,
      {
        ...NOTIFICATION_DEFAULT_CONFIG,
        ...globalConfig,
      },
    );
  }
Example #7
Source File: message.service.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    overlay: Overlay,
    injector: Injector,
    applicationRef: ApplicationRef,
    cfr: ComponentFactoryResolver,
    @Optional()
    @Inject(MESSAGE_CONFIG)
    globalConfig: MessageGlobalConfig,
  ) {
    super(
      overlay,
      injector,
      applicationRef,
      cfr,
      'aui-message-overlay-pane',
      MessageWrapperComponent,
      MessageComponent,
      {
        ...MESSAGE_DEFAULT_CONFIG,
        ...globalConfig,
      },
    );
  }
Example #8
Source File: base-message.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    protected overlay: Overlay,
    protected injector: Injector,
    protected applicationRef: ApplicationRef,
    protected cfr: ComponentFactoryResolver,
    protected overlayPaneClassName: string,
    protected wrapperClass: ComponentType<Wrapper>,
    protected componentClass: ComponentType<Component>,
    protected globalConfig: MessageGlobalConfig,
  ) {
    this.initWrapperContainer();
  }
Example #9
Source File: menu-content.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    private readonly templateRef: TemplateRef<unknown>,
    private readonly appRef: ApplicationRef,
    private readonly viewContainerRef: ViewContainerRef,
    private readonly componentFactoryResolver: ComponentFactoryResolver,
    private readonly injector: Injector,
    @Inject(DOCUMENT) document: any,
  ) {
    this.doc = document;
  }
Example #10
Source File: home.component.ts    From msfs-community-downloader with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(
        private app: ApplicationRef,
        private settingsService: SettingsService,
        private router: Router,
        private domainService: DomainService) {

        this.errorSub = this.domainService.errorSubject.subscribe(err => {
            this.displayError(err);
        });
    }
Example #11
Source File: platform-core.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
protected pageStatus = {
    destroy: function (this: MiniProgramComponentInstance) {
      if (this.__ngDestroy) {
        this.__ngDestroy();
      }
    },
    attachView: function (this: MiniProgramComponentInstance) {
      if (this.__ngComponentInjector && this.__isDetachView) {
        const applicationRef = this.__ngComponentInjector.get(ApplicationRef);
        applicationRef.attachView(this.__ngComponentHostView);
        this.__isDetachView = false;
      }
    },
    detachView: function (this: MiniProgramComponentInstance) {
      if (this.__ngComponentInjector) {
        this.__isDetachView = true;
        const applicationRef = this.__ngComponentInjector.get(ApplicationRef);
        applicationRef.detachView(this.__ngComponentHostView);
      }
    },
  };
Example #12
Source File: app.component.ts    From 1hop with MIT License 6 votes vote down vote up
constructor(
        protected web3Service: Web3Service,
        protected configurationService: ConfigurationService,
        protected themeService: ThemeService,
        protected swUpdate: SwUpdate,
        protected appRef: ApplicationRef,
        @Inject(DOCUMENT) private document: Document
    ) {

    }
Example #13
Source File: modals.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(
    @Inject(DOCUMENT)
    private readonly document: Document,
    private readonly rendererFactory: RendererFactory2,
    private readonly appRef: ApplicationRef,
    private readonly componentFactoryResolver: ComponentFactoryResolver,
    private readonly injector: Injector,
  ) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }
Example #14
Source File: modals.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
async open<T = any>(data: IModalOpenParams): Promise<IModalOpenReturns<T>> {
    const componentRef = this.componentFactoryResolver
      .resolveComponentFactory(ModalContainerComponent)
      .create(this.injector);

    componentRef.instance.childComponent = data.component;

    if (!!data.componentInputs) {
      componentRef.instance.childComponentInputs = data.componentInputs;
    }

    this.appRef.attachView(componentRef.hostView);

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

    this.renderer.appendChild(this.document.body, rootNode);

    componentRef.instance.closeModal$
      .pipe(take(1))
      .subscribe(() => {
        this.appRef.detachView(componentRef.hostView);
        componentRef.destroy();
      });

    return componentRef.instance.createdComponent$
      .pipe(take(1))
      .toPromise()
      .then(childComponentRef => ({
        modalContainer: componentRef,
        componentRef: childComponentRef
      }));
  }
Example #15
Source File: loading.directive.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
appLoadingSubscription: Subscription = this.appLoading$
    .pipe(takeUntil(this.componentDestroyed$))
    .pipe(filter(status => !(!status && !this.loadingComponentRef)))
    .subscribe((status) => {
      if (!!status) {
        this.loadingComponentRef = this.componentFactoryResolver.resolveComponentFactory(PulseLoadingComponent)
          .create(this.vcr.injector);

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

        this.renderer.appendChild(this.el.nativeElement, this.rootNode);
      } else {
        this.renderer.removeChild(this.el.nativeElement, this.rootNode);
        this.loadingComponentRef.destroy();
      }
    });
Example #16
Source File: component-creator.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(
    @Inject(DOCUMENT)
    private readonly document: Document,
    private readonly rendererFactory: RendererFactory2,
    private readonly appRef: ApplicationRef,
    private readonly componentFactoryResolver: ComponentFactoryResolver,
    private readonly injector: Injector,
    private ngZone: NgZone
  ) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }
Example #17
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 #18
Source File: app.component.ts    From 1x.ag with MIT License 6 votes vote down vote up
constructor(
        protected web3Service: Web3Service,
        protected configurationService: ConfigurationService,
        protected themeService: ThemeService,
        protected swUpdate: SwUpdate,
        protected appRef: ApplicationRef,
        private deviceDetectorService: DeviceDetectorService,
        @Inject(DOCUMENT) private document: Document
    ) {

    }
Example #19
Source File: bar.drag.spec.ts    From ngx-gantt with MIT License 5 votes vote down vote up
describe('bar-drag', () => {
    let fixture: ComponentFixture<TestGanttBarComponent>;
    let ganttComponentInstance: TestGanttBarComponent;
    let ganttDebugElement: DebugElement;

    beforeEach(async () => {
        TestBed.configureTestingModule({
            imports: [CommonModule, NgxGanttModule],
            declarations: [TestGanttBarComponent]
        }).compileComponents();
        fixture = TestBed.createComponent(TestGanttBarComponent);
        ganttDebugElement = fixture.debugElement.query(By.directive(NgxGanttComponent));
        ganttComponentInstance = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should active when mouse enter bar', () => {
        const barElement = fixture.debugElement.query(By.directive(NgxGanttBarComponent)).nativeElement;
        dispatchMouseEvent(barElement, 'mouseenter');
        expect(barElement.classList).toContain(activeClass);
        dispatchMouseEvent(barElement, 'mouseleave');
        expect(barElement.classList).not.toContain(activeClass);
    });

    it('should bar drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[0];
        dragEvent(fixture, bar.nativeElement);
        expect(bar.componentInstance.item.start.getUnixTime()).toEqual(new GanttDate('2020-04-21 00:00:00').getUnixTime());
        expect(bar.componentInstance.item.end.getUnixTime()).toEqual(new GanttDate('2020-06-26 23:59:59').getUnixTime());
    });

    it('should first bar handle drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[1];
        const firstHandleElement = bar.queryAll(By.css('.drag-handles .handle'))[0].nativeElement;
        dragEvent(fixture, firstHandleElement, bar.nativeElement);
        expect(bar.componentInstance.item.start.getUnixTime()).toEqual(new GanttDate('2020-05-14 00:00:00').getUnixTime());
    });

    it('should last bar handles drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[1];
        const lastHandleElement = bar.queryAll(By.css('.drag-handles .handle'))[1].nativeElement;
        dragEvent(fixture, lastHandleElement, bar.nativeElement);
        expect(bar.componentInstance.item.end.getUnixTime()).toEqual(new GanttDate('2020-07-15 23:59:59').getUnixTime());
    });

    it('should first bar link handle drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[2];
        const firstHandleElement = bar.queryAll(By.css('.link-handles .handle'))[0].nativeElement;
        linkDragEvent(fixture, firstHandleElement);
    });

    it('should last bar link handles drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[2];
        const lastHandleElement = bar.queryAll(By.css('.link-handles .handle'))[1].nativeElement;
        linkDragEvent(fixture, lastHandleElement);
    });

    it('should not run change detection when the `mousedown` is dispatched on the handle', () => {
        const appRef = TestBed.inject(ApplicationRef);
        spyOn(appRef, 'tick');
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[0];
        const firstHandleElement = bar.queryAll(By.css('.drag-handles .handle'))[0].nativeElement;
        const event = new Event('mousedown');
        spyOn(event, 'stopPropagation').and.callThrough();
        firstHandleElement.dispatchEvent(event);
        expect(appRef.tick).not.toHaveBeenCalled();
        expect(event.stopPropagation).toHaveBeenCalled();
    });
});
Example #20
Source File: page.service.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
constructor(
    private injector: Injector,
    private applicationRef: ApplicationRef,
    @Inject(APP_TOKEN) private app: AppOptions,
    private ngZone: NgZone
  ) {}
Example #21
Source File: tour-service.service.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
constructor(
    private readonly tourStoreService: TourStoreServiceService,
    private readonly router: Router,
    private readonly componentFactory: ComponentFactoryResolver,
    private readonly injector: Injector,
    private readonly appRef: ApplicationRef,
  ) {}
Example #22
Source File: load-component.service.ts    From sba-angular with MIT License 5 votes vote down vote up
constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private applicationRef: ApplicationRef) {
    }
Example #23
Source File: angular-context.ts    From s-libs with MIT License 5 votes vote down vote up
protected runChangeDetection(): void {
    this.inject(ApplicationRef).tick();
  }
Example #24
Source File: ngx-view.service.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
constructor(private appRef: ApplicationRef) {}
Example #25
Source File: main.ts    From Elastos.Essentials.App with MIT License 5 votes vote down vote up
platformBrowserDynamic().bootstrapModule(AppModule).then((module) => {
  let applicationRef = module.injector.get(ApplicationRef);
  let appComponent = applicationRef.components[0];
  enableDebugTools(appComponent);
  Logger.log("global", "App module bootstrap complete");
}).catch(err => console.log(err));
Example #26
Source File: theme-builder-dynamic-component.component.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private injector: Injector,
    private appRef: ApplicationRef,
    public viewContainerRef: ViewContainerRef,
    private themeBuilderService: ThemeBuilderService
  ) {
  }
Example #27
Source File: dynamic-component.component.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private injector: Injector,
    private appRef: ApplicationRef,
    public viewContainerRef: ViewContainerRef
  ) {
  }
Example #28
Source File: anchor.directive.ts    From alauda-ui with MIT License 5 votes vote down vote up
constructor(
    private readonly cfr: ComponentFactoryResolver,
    private readonly appRef: ApplicationRef,
    private readonly injector: Injector,
    public readonly elRef: ElementRef<HTMLElement>,
    @Optional() private readonly cdkScrollable: CdkScrollable,
  ) {}
Example #29
Source File: domain.service.ts    From msfs-community-downloader with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(
        private app: ApplicationRef,
        private packageService: PackagesService,
        private filesystemService: FilesystemService,
        private githubService: GithubService,
        private downloaderService: DownloaderService,
        private extractorService: ExtractorService,
        private settingsService: SettingsService,
        private electronService: ElectronService
    ) {
        this.downloadSub = downloaderService.fileDownloaded.subscribe(r => {
            if (r) {
                this.processDownloadedFile(r);
            }
        });
        this.downloadUpdateSub = downloaderService.fileDownloadedUpdated.subscribe(r => {
            if (r) {
                this.processDownloadedUpdate(r);
            }
        });
        this.extractSub = extractorService.fileExtracted.subscribe(r => {
            if (r) {
                this.processExtractedFolder(r);
            }
        });
        this.copySub = filesystemService.folderCopied.subscribe(r => {
            if (r) {
                this.processCopiedFolder(r);
            }
        });

        this.electronService.ipcRenderer.on('log-error', (event, arg) => {
            if (arg) {
                const error = arg.error;
                const info: FilePackageInfo = arg.info;

                this.processPackageError(info);

                console.error('Node error');
                console.error(error);

                if (error.message) {
                    this.errorSubject.next(error.message);
                } else {
                    this.errorSubject.next(error);
                }
            }
        });
    }