@angular/core#Type TypeScript Examples

The following examples show how to use @angular/core#Type. 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: create-spy-object.ts    From s-libs with MIT License 6 votes vote down vote up
// adapted from https://github.com/ngneat/spectator/blob/e13c9554778bdb179dfc7235aedb4b3b90302850/projects/spectator/src/lib/mock.ts

/**
 * Creates a new object with jasmine spies for each method in `type`.
 *
 * ```ts
 * class Greeter {
 *   greet(name: string) {
 *     return `Hello, ${name}!`;
 *   }
 * }
 *
 * const spyObject = createSpyObject(Greeter);
 * spyObject.greet.and.returnValue("Hello, stub!");
 * expect(spyObject.greet("Eric")).toBe("Hello, stub!");
 * expectSingleCallAndReset(spyObject.greet, "Eric");
 * ```
 */
export function createSpyObject<T>(type: Type<T>): jasmine.SpyObj<T> {
  const mock: any = {};
  for (
    let proto = type.prototype;
    proto !== null;
    proto = Object.getPrototypeOf(proto)
  ) {
    for (const key of functions(proto)) {
      mock[key] = jasmine.createSpy(key);
    }
  }
  return mock;
}
Example #2
Source File: dialog.service.ts    From mysteryofthreebots with Apache License 2.0 6 votes vote down vote up
open(component: Type<any>) {
    let componentRef = this.componentCache.get(component);
    if (!componentRef) {
      const componentFactory = this.resolver.resolveComponentFactory(component);
      componentRef = componentFactory.create(this.injector);
      this.componentCache.set(component, componentRef);
      this.appRef.attachView(componentRef.hostView);
      const closeDialog = (componentRef.instance as any).closeDialog;
      if (closeDialog && closeDialog instanceof EventEmitter) {
        (closeDialog as EventEmitter<void>).subscribe(() => {
          this.close();
        });
      }
    }
    if (!this.backdrop) {
      this.backdrop = this.document.getElementById('app-dialog-backdrop');
    }
    if (!this.dialog) {
      this.dialog = this.document.getElementById('app-dialog');
      this.dialog.addEventListener('close-dialog', this.handleCloseDialog, true);
    }
    this.renderer.addClass(this.backdrop, 'is-open');
    this.dialog.innerHTML = '';
    this.renderer.appendChild(this.dialog, (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]);
  }
Example #3
Source File: shared.module.ts    From ngx-ui-tour with MIT License 6 votes vote down vote up
// Following workaround is only needed because every parent uses different tour anchor implementation
    static withAnchorDirectiveType<T extends TourAnchorDirective>(anchorDirectiveType: Type<T>): ModuleWithProviders<SharedModule> {
        return {
            ngModule: SharedModule,
            providers: [{
                provide: TOUR_ANCHOR_DIRECTIVE_TYPE,
                useValue: anchorDirectiveType
            }]
        };
    }
Example #4
Source File: base-drawer.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
createDrawerConfig(component: Type<NzSafeAny>, drawerOptions: NzDrawerOptions = {}, params: object = {}): NzDrawerOptions {
    const defaultOptions: NzDrawerOptions = {
      nzContent: component,
      nzClosable: false,
      nzContentParams: {
        params
      },
      nzFooter: this.btnTpl
    };
    return _.merge(defaultOptions, drawerOptions);
  }
Example #5
Source File: monaco-editor.spec.ts    From ng-util with MIT License 6 votes vote down vote up
describe('ng-util: monaco-editor', () => {
  function create<T>(comp: Type<T>, option: { html?: string } = {}): ComponentFixture<T> {
    TestBed.configureTestingModule({
      imports: [
        NuMonacoEditorModule.forRoot({
          baseUrl: `monaco-editor/min`,
        }),
      ],
      declarations: [TestComponent, TestDiffComponent],
    });
    if (option.html != null) TestBed.overrideTemplate(comp, option.html);
    return TestBed.createComponent(comp);
  }

  xit('should be working', done => {
    const fixture = create(TestComponent);
    fixture.componentInstance.options = { readOnly: true };
    const changeSpy = spyOn(fixture.componentInstance, 'onChange');
    fixture.detectChanges();
    setTimeout(() => {
      expect(changeSpy).toHaveBeenCalled();
      expect(changeSpy.calls.first().args[0].type).toBe(`init`);
      done();
    }, FIX_LOAD_LIB_TIME);
  });
});
Example #6
Source File: np-modal-ref.ts    From np-ui-lib with MIT License 6 votes vote down vote up
constructor(
    public overlay: OverlayRef,
    public content: string | TemplateRef<any> | Type<any>,
    public config: NpModalConfig,
    public data: any
  ) {
    overlay.backdropClick().subscribe(() => {
      if (config.closeOnClickOutside === true) {
        this._close(null);
      }
    });
  }
Example #7
Source File: nas-model.directive.spec.ts    From s-libs with MIT License 6 votes vote down vote up
function initTest<C, S>(
  component: Type<C>,
  storeType: Type<S>,
  {
    extraDirectives = [] as Array<Type<any>>,
    template = '',
    beforeCreate = noop,
  } = {},
): S {
  if (template) {
    TestBed.overrideComponent(component, { set: { template } });
  }
  TestBed.configureTestingModule({
    declarations: [component, ...extraDirectives],
    imports: [FormsModule, NasModelModule],
    providers: [storeType],
  });

  beforeCreate();
  fixture = TestBed.createComponent<C>(component);
  return TestBed.inject(storeType);
}
Example #8
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 #9
Source File: preview.service.ts    From sba-angular with MIT License 6 votes vote down vote up
constructor(
        @Optional() @Inject(PREVIEW_MODAL) public previewModal: Type<any>,
        private router: Router,
        private previewWebService: PreviewWebService,
        private appService: AppService,
        private authenticationService: AuthenticationService,
        private searchService: SearchService,
        private modalService: ModalService,
        private recentDocumentsService: RecentDocumentsService,
        public exprBuilder: ExprBuilder,
        private domSanitizer: DomSanitizer) {

        // Subscribe to own events and add documents to the recent documents service
        this.events.subscribe(event => {
            if(event.record && (event.type === PreviewEventType.Modal || event.type === PreviewEventType.Route || event.type === PreviewEventType.Window)){
                this.recentDocumentsService.addDocument(event.record, false);
            }
        });
    }
Example #10
Source File: task-bar.component.ts    From StraxUI with MIT License 6 votes vote down vote up
public open<T>(component: Type<T>, data?: any, taskBarOptions?: TaskBarOptions): T {
    this.options.next(taskBarOptions || {});
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
    const viewContainerRef = this.host.viewContainerRef;
    viewContainerRef.clear();

    try {
      const componentRef = viewContainerRef.createComponent(componentFactory);
      if (data) {
        Object.keys(data).forEach(key => {
          componentRef.instance[key] = data[key];
        });
      }
      this.opened = true;
      return componentRef.instance;

    } catch (e) {
      console.log(e);
    }
    return null;
  }
Example #11
Source File: message-dialog.component.ts    From dev-manager-desktop with Apache License 2.0 6 votes vote down vote up
ngAfterViewInit(): void {
    if (this.message instanceof Type) {
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.message);
      this.messageComponent.clear();
      let providers: StaticProvider[] = [];
      if (this.messageExtras) {
        providers = Object.getOwnPropertyNames(this.messageExtras).map(name => ({ provide: name, useValue: this.messageExtras[name] }));
      }
      this.messageComponent.createComponent(componentFactory, null, Injector.create({ providers }));
      this.changeDetector.detectChanges();
    }
  }
Example #12
Source File: directives.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
SHARED_FORM_DIRECTIVES: Type<any>[] = [
  NgNoValidate,
  NgSelectOption,
  NgSelectMultipleOption,
  DefaultValueAccessor,
  SliderValueAccessor,
  RangeValueAccessor,
  CheckboxControl,
  SelectControlValueAccessor,
  SelectMultipleControlValueAccessor,
  RadioControl,
  NgControlStatus,
  NgControlStatusGroup,
  RequiredValidator,
  MinLengthValidator,
  MaxLengthValidator,
  PatternValidator,
  CheckboxRequiredValidator,
  EmailValidator,
  MinValidator,
  MaxValidator,
  SwitchValueAccessor,
  PickerViewValueAccessor,
  PickerValueAccessor,
  RadioGroupValueAccessor,
  CheckBoxGroupValueAccessor,
]
Example #13
Source File: route.component.ts    From router with MIT License 6 votes vote down vote up
private loadAndRender(route: Route) {
    if (route.load) {
      return from(
        route
          .load()
          .then(
            (componentOrModule: NgModuleRef<ModuleWithRoute> | Type<any>) => {
              let component: Type<any>;

              if ((componentOrModule as any).ɵmod) {
                const moduleRef: NgModuleRef<ModuleWithRoute> =
                  createNgModuleRef(
                    componentOrModule as Type<any>,
                    this.viewContainerRef.injector
                  );
                component = moduleRef.instance.routeComponent;
              } else {
                component = componentOrModule as Type<any>;
              }

              this.renderComponent(component);
            }
          )
      );
    } else {
      this.showTemplate();
      return of(true);
    }
  }
Example #14
Source File: component-mapping.ts    From aem-angular-editable-components with Apache License 2.0 6 votes vote down vote up
/**
 * Stores a component class for the given resource types and also allows to provide an EditConfig object
 * @param resourceTypes - List of resource types
 * @type Model - The Model interface / class type that will be Mapped. Bound to the EditConfig configuration.
 */
function MapTo<Model extends MappedComponentProperties = any>(resourceTypes: string | string[]) {
  /**
   * @param clazz - Component class to be stored
   * @param [editConfig] - Edit configuration to be stored for the given resource types
   */
   return (clazz:Type<Model>, editConfig:EditConfig<Model> = null): void =>
     componentMapping.map(resourceTypes, clazz, editConfig);
}
Example #15
Source File: drawer.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
private attachBodyContent(): void {
    this.bodyPortalOutlet?.dispose();
    const content = this.content || this.contentTemplate;
    if (content instanceof Type) {
      const componentPortal = new ComponentPortal<T>(
        content,
        null,
        Injector.create({
          providers: [
            {
              provide: DATA,
              useValue: this.contentParams,
            },
          ],
          parent: this.injector,
        }),
      );
      const componentRef =
        this.bodyPortalOutlet?.attachComponentPortal(componentPortal);
      this.componentInstance = componentRef.instance;
      Object.assign(componentRef.instance, this.contentParams);
      componentRef.changeDetectorRef.detectChanges();
    }
  }
Example #16
Source File: authorization.interceptor.ts    From alura_angular_rxjs_1 with MIT License 6 votes vote down vote up
appendTokenToRequest(request: HttpRequest<any>): HttpRequest<any> {
    const authService: AuthorizationService = this.injector.get<
      AuthorizationService
    >(AuthorizationService as Type<AuthorizationService>);
    const token = authService.getAuthenticatedUser().token;
    return request.clone({
      headers: request.headers.set('x-access-token', token),
    });
  }
Example #17
Source File: aem-component.directive.ts    From aem-angular-editable-components with Apache License 2.0 6 votes vote down vote up
/**
   * Renders a component dynamically based on the component definition
   *
   * @param componentDefinition The component definition to render
   */
  private renderComponent(componentDefinition: Type<MappedComponentProperties>) {
    if (componentDefinition) {
      const factory = this.factoryResolver.resolveComponentFactory(componentDefinition);

      this.renderWithFactory(factory);
    } else {
      throw new Error('No component definition!!');
    }
  }
Example #18
Source File: popup.service.ts    From t3mpl-editor with MIT License 6 votes vote down vote up
public open<R, T extends PopupComponent<R>>(type: Type<T>, setup: (instance: T) => void): Observable<R> {
		if (!this.container) {
			throw new Error('The container is required.');
		}

		const factory = this.factoryResolver.resolveComponentFactory(type);
		const component = factory.create(this.container.injector);
		setup(component.instance);
		this.container.insert(component.hostView);

		return component.instance.result
			.pipe(map(r => {
				this.container.remove();
				return r;
			}));
	}
Example #19
Source File: aem-component.directive.ts    From aem-angular-editable-components with Apache License 2.0 6 votes vote down vote up
async initializeAsync() {
   const lazyMappedPromise: Promise<Type<MappedComponentProperties>> = ComponentMapping.lazyGet<MappedComponentProperties>(this.type);

   try {
     const LazyResolvedComponent = await lazyMappedPromise;

     this.renderComponent(LazyResolvedComponent);
     this.loaded = true;
     this._changeDetectorRef.detectChanges();
   } catch (err) {
     console.warn(err);
   }
  }
Example #20
Source File: paginator.directive.spec.ts    From angular-custom-material-paginator with MIT License 6 votes vote down vote up
function createComponent<T>(type: Type<T>, providers: Provider[] = []): ComponentFixture<T> {
  TestBed.configureTestingModule({
    imports: [MatPaginatorModule, NoopAnimationsModule],
    declarations: [type, PaginatorDirective],
    providers: [MatPaginatorIntl, ...providers]
  }).compileComponents();
  const fixture = TestBed.createComponent(type);
  fixture.detectChanges();
  return fixture;
}
Example #21
Source File: aem-component.directive.ts    From aem-angular-editable-components with Apache License 2.0 6 votes vote down vote up
async ngOnInit() {

    if (this.type) {
     const mappedFn:Type<MappedComponentProperties> = ComponentMapping.get<MappedComponentProperties>(this.type);
 
     if (mappedFn) {
      this.renderComponent(mappedFn);
     } else {
      await this.initializeAsync();
     }
    } else {
     console.warn('no type on ' + this.cqPath);
    }
 
   }
Example #22
Source File: settings-container.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public getSettingsComponent(): PolymorpheusComponent<
    SettingsItComponent | SettingsBridgeComponent | SettingsCcrComponent,
    Injector
  > {
    let component;
    switch (this.swapService.swapMode) {
      case SWAP_PROVIDER_TYPE.INSTANT_TRADE:
        component = SettingsItComponent;
        break;
      case SWAP_PROVIDER_TYPE.BRIDGE:
        component = SettingsBridgeComponent;
        break;
      default:
        component = SettingsCcrComponent;
    }
    return new PolymorpheusComponent(
      component as Type<SettingsItComponent | SettingsBridgeComponent | SettingsCcrComponent>
    );
  }
Example #23
Source File: dynamicHooks.m.ts    From ngx-dynamic-hooks with MIT License 6 votes vote down vote up
// Make sure to set the optional function signature "ModuleWithProviders<T>".
  // Note: This will break Angular 5 backwards compatibility, but enable compatibility with newer versions (13+?).
  static forRoot(globalSettings: DynamicHooksGlobalSettings, platformService?: Type<PlatformService>): ModuleWithProviders<DynamicHooksModule> {
    return {
      ngModule: DynamicHooksModule,
      providers: [
        // Put app-wide services here
        { provide: DYNAMICHOOKS_GLOBALSETTINGS, useValue: globalSettings },
        OutletService,
        DataTypeEncoder,
        DataTypeParser,
        DeepComparer,
        HookFinder,
        { provide: PlatformService, useClass: platformService || PlatformBrowserService }
      ]
    };
  }
Example #24
Source File: modal.service.ts    From sba-angular with MIT License 5 votes vote down vote up
MODAL_PROMPT = new InjectionToken<Type<any>>('MODAL_PROMPT')
Example #25
Source File: component-mapping.ts    From aem-angular-editable-components with Apache License 2.0 5 votes vote down vote up
/**
     * Returns the component class Promise for the given resourceType
     * @param resourceType - Resource type for which the component class has been stored
     * @type Model - The Model interface / class type bound to the editconfig object.
     */
    lazyGet<Model extends MappedComponentProperties = any>(resourceType: string): Promise<Type<Model>> {
        return this.spaMapping.getLazy(resourceType) as Promise<Type<Model>>;
    }
Example #26
Source File: login.service.ts    From sba-angular with MIT License 5 votes vote down vote up
MODAL_LOGIN = new InjectionToken<Type<any>>('MODAL_LOGIN')
Example #27
Source File: component-mapping.ts    From aem-angular-editable-components with Apache License 2.0 5 votes vote down vote up
/**
   * Returns the component class for the given resourceType
   * @param resourceType - Resource type for which the component class has been stored
   * @type Model - The Model interface / class type bound to the editconfig object.
   */
  get<Model extends MappedComponentProperties = any>(resourceType:string):Type<Model> {
    return this.spaMapping.get(resourceType) as Type<Model>;
  }
Example #28
Source File: modal.service.ts    From sba-angular with MIT License 5 votes vote down vote up
/**
     * Open a modal dialog using the passed configuration options.
     *
     * @param component The type of the component to use for the modal.
     * @param config Configuration options for the modal.
     * @retuns An `IModalRef` object that can be used to close the modal.
     */
    openRef(component: Type<any>, config: ModalConfig = {}): IModalRef {
        // Override default configuration
        const modalConfig = { ...DEFAULT_CONFIG, ...config };
        if (modalConfig.fullscreen) {
            modalConfig.width = "100%";
            modalConfig.height = "100%";
            if (Utils.isString(modalConfig.panelClass)) {
                modalConfig.panelClass = [modalConfig.panelClass, "sq-modal-fullscreen"];
            }
            else if (modalConfig.panelClass) {
                modalConfig.panelClass.push("sq-modal-fullscreen");
            }
            else {
                modalConfig.panelClass = "sq-modal-fullscreen";
            }
        }
        // Returns an OverlayRef which is a PortalHost
        const overlayRef = this.createOverlay(modalConfig);
        // Instantiate remote control
        const modalRef = new ModalRef(overlayRef);
        const overlayComponent = this.attachDialogContainer(component, overlayRef, modalConfig, modalRef);
        modalRef.componentInstance = overlayComponent;
        overlayRef.hostElement.classList.add("sq-modal-host");
        if (modalConfig.closeOnBackdropClick) {
            // NB backdropClick will not fire if pointer-events are enabled on modal-host
            overlayRef.backdropClick().subscribe(() => modalRef.close());
            // Provide support for a scrollable sq-modal-host (overlay wrapper)
            // The standard cdk styling disables pointer-events at this level which means that scrolling
            // won't work. We can enable pointer-events in css but then the backdrop will not receive the
            // click event. So, we handle the click event directly on sq-modal-host also and if the
            // click target === sq-modal-host then we initiate modal closing here
            overlayRef.hostElement.addEventListener("click", (event) => {
                if (event.target === overlayRef.hostElement) {
                    modalRef.close();
                }
            });
        }
        overlayRef.keydownEvents().subscribe((event) => {
            if (event.keyCode === Keys.esc) {
                modalRef.close();
            }
        });
        modalRef.disableSubmit();
        return modalRef;
    }
Example #29
Source File: platform-core.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
protected getPageOptions(component: Type<unknown> & MiniProgramPageOptions) {
    return component.mpPageOptions as WechatMiniprogram.Page.Options<{}, {}>;
  }