@angular/common#isPlatformBrowser TypeScript Examples

The following examples show how to use @angular/common#isPlatformBrowser. 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: checkout.component.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Initially calls initCheckoutForm function
  ngOnInit() {
    this.initCheckoutForm();
    this.getSessionData();
    if (isPlatformBrowser(this.platformId)) {
      if (localStorage.getItem('userToken')) {
        this.commonSandbox.doGetProfile();
        this.setProfileDetails();
      }
    }
    this.imagePath = environment.imageUrl;
  }
Example #2
Source File: app.component.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
constructor(
    private router: Router,
    private loadingBarService: LoadingBarService,
    public appService: AppService,
    @Inject(PLATFORM_ID) private platformId: unknown,
    @Inject(APP_ID) private appId: string,
  ) {
    if (isPlatformBrowser(platformId))
      this.router.events.subscribe(this.navigationInterceptor.bind(this));
  }
Example #3
Source File: ngx-splide.component.ts    From ngx-splide with MIT License 6 votes vote down vote up
ngAfterViewInit()
    {
        if (!isPlatformBrowser(this.platformId))
            return;
            
        this.splide = new Splide(this.splideElement.nativeElement, this.options);
        if (this.syncWith) {
            this.splide.sync(this.syncWith.getSplideInstance());
        }

        this.onInit.emit(this.splide);
        this.addEventListeners();
        this.splide.mount();

        const slidesSubscription = this.slides.changes
            .subscribe((list: QueryList<NgxSplideSlideComponent>) => {
                this.cdr.detectChanges();

                setTimeout(() => {
                    this.splide.destroy();
                    this.splide.mount();

                    this.addEventListeners();
                });
            })
        ;

        this.cdr.detectChanges();
    }
Example #4
Source File: company-stocks-chart.component.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
constructor(private companiesService: CustomersService, @Inject(PLATFORM_ID) platform: object) {
    this.isBrowser = isPlatformBrowser(platform);
    this.companiesService.getCompaniesStock().subscribe(x => this.data = this.filteredData = x);
    this.companiesService.customerSelection.subscribe(d => {
      this.filteredData = this.data.filter(c => d.find(entry => entry === c[0].companyId));
      if (!this.filteredData.length) {
        this.filteredData = this.data;
      }
    });
  }
Example #5
Source File: auth.effects.ts    From svvs with MIT License 6 votes vote down vote up
signIn$ = createEffect(() =>
    this.dataPersistence.fetch<IActionEffectPayload<IActionForcePayload>>(AuthActions.signIn, {
      run: (action, store) => {
        return isPlatformBrowser(this.platformId) && (!this.getState(store).signInRun || action.payload.force)
          ? AuthActions.signInRun()
          : AuthActions.signInCancel()
      },
      onError: (action, error) => this.errorHandler(action, error)
    }),
  )
Example #6
Source File: image-viewer.component.ts    From nghacks with MIT License 6 votes vote down vote up
@HostListener('window:resize', ['$event'])
  private setImageDimension(): void {

    if (!isPlatformBrowser(this._platformId)) { return; }

    const windowDimension = new ImageDimension(
      this.percentage(this._document.body.clientWidth, 90),
      this.percentage(this._document.body.clientHeight, 90)
    );
    this.calculatedImageDimension = this.calculateAspectRatioFit(this._originalImageDimension, windowDimension);
  }
Example #7
Source File: top-menu.component.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**first clear the local storage data.
   * calls commonSandbox doSignout,
   * Then navigate to authentication module
   * */
  signOut() {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.clear();
      sessionStorage.clear();
    }
    this.commonSandbox.doSignout();
    this.productControl.clearCart();
    this.router.navigate(['/auth']);
  }
Example #8
Source File: header.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    @Inject(PLATFORM_ID) platformId: Object,
    private readonly headerStore: HeaderStore,
    private readonly authService: AuthService,
    private readonly iframeService: IframeService,
    private readonly cdr: ChangeDetectorRef,
    private readonly storeService: StoreService,
    private readonly router: Router,
    private readonly errorService: ErrorsService,
    private readonly queryParamsService: QueryParamsService,
    private readonly swapFormService: SwapFormService,
    private readonly swapsService: SwapsService,
    private readonly myTradesService: MyTradesService,
    private readonly tokensService: TokensService,
    @Inject(WINDOW) private readonly window: Window,
    @Inject(DOCUMENT) private readonly document: Document,
    @Self() private readonly destroy$: TuiDestroyService,
    private readonly gtmService: GoogleTagManagerService,
    private readonly zone: NgZone
  ) {
    this.loadUser();
    this.advertisementType = 'default';
    this.currentUser$ = this.authService.getCurrentUser();
    this.isMobileMenuOpened$ = this.headerStore.getMobileMenuOpeningStatus();
    this.isMobile$ = this.headerStore.getMobileDisplayStatus();
    this.headerStore.setMobileDisplayStatus(this.window.innerWidth <= this.headerStore.mobileWidth);
    if (isPlatformBrowser(platformId)) {
      this.zone.runOutsideAngular(() => {
        this.setNotificationPosition();
        this.window.onscroll = () => {
          this.setNotificationPosition();
        };
      });
    }
    this.swapType$ = this.swapsService.swapMode$;
  }
Example #9
Source File: cart.component.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// navigation to checkout component.And set local storage
  public checkoutPage() {
    const checkoutToken = '1';
    this.router.navigate(['/checkout']);
    if (isPlatformBrowser(this.platformId)) {
      localStorage.setItem('checkout', checkoutToken);
    }
  }
Example #10
Source File: slick-item.directive.ts    From flingo with MIT License 5 votes vote down vote up
ngOnInit() {
        if (isPlatformBrowser(this.platformId)) {
            this.carousel.addSlide(this);
        }
    }
Example #11
Source File: products.component.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
constructor(
    private activatedRoute: ActivatedRoute,
    public dialog: MatDialog,
    public snackBar: MatSnackBar,
    private router: Router,
    public listSandbox: ListsSandbox,
    private configService: ConfigService,
    private changeDetectRef: ChangeDetectorRef,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {
    // subscribe route params
    this.subscription.push(
      this.activatedRoute.queryParams.subscribe(query => {
        if (query['keyword']) {
          this.keyword = query['keyword'];
          if (isPlatformBrowser(this.platformId)) {
            localStorage.setItem('keywordData', query['keyword']);
            this.keyword = localStorage.getItem('keywordData');
          }
          this.getProductList(this.startKey, this.viewOrder, this.categoryId);
        }
        if (query['brand']) {
          this.brand = query['brand'];
          this.getProductList(this.startKey, this.viewOrder, this.categoryId);
        }
      })
    );
    this.subscription.push(
      this.activatedRoute.params.subscribe(param => {
        this.queryParams = param;

        // if route params contains id assign id to the parameter categoryId
        if (this.queryParams.id) {
          if (this.queryParams.id === 'All' && !this.brand) {
            this.isClicked = [];
            this.brand = '';
            this.keyword = '';
            this.categoryId = '';
            this.getProductList(this.startKey, this.viewOrder, this.categoryId);
          } else {
            this.isClicked = [];
            this.isClicked[this.queryParams.id] = true;
            this.categoryId = this.queryParams.id;
            this.getProductList(this.startKey, this.viewOrder, this.categoryId);
          }
        }
      })
    );
  }
Example #12
Source File: search.component.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
focusInput() {
    if (isPlatformBrowser(this.platformId)) {
      this.searchInputElement.nativeElement.focus();
    }
  }
Example #13
Source File: window.service.ts    From ng-ant-admin with MIT License 5 votes vote down vote up
constructor(@Inject(PLATFORM_ID) private platformId: object) {
    this.isBrowser = isPlatformBrowser(this.platformId);
  }
Example #14
Source File: app.component.ts    From App with MIT License 5 votes vote down vote up
constructor(
		@Inject(PLATFORM_ID) platformId: any,
		iconRegistry: MatIconRegistry,
		sanitizer: DomSanitizer,
		appService: AppService,
		titleService: Title,
		localStorageSvc: LocalStorageService,
		private windowRef: WindowRef,
		private sw: SwUpdate,
		private dialog: MatDialog,
		private location: Location,
		private router: Router,
		private overlayRef: OverlayContainer,
		public viewportService: ViewportService
	) {
		// Check if platform is browser
		AppComponent.isBrowser.next(isPlatformBrowser(platformId));

		for (const iconRef of iconList) {
			iconRegistry.addSvgIcon(
				iconRef[0],
				sanitizer.bypassSecurityTrustResourceUrl(`assets/${iconRef[1]}`)
			);
		}

		// Set page title
		{
			router.events.pipe( // Handle "ActivationStart" router event
				filter(ev => ev instanceof ActivationStart),
				map(ev => ev as ActivationStart),

				// Find variables and omit them from the title.
				// Components can call AppService.pushTitleAttributes() to update them
				tap(ev => {
					const title: string = '7TV - ' + (ev.snapshot.data?.title ?? 'Untitled Page' as string);

					appService.pageTitleSnapshot = String(title);
					titleService.setTitle(`${title?.replace(AppService.PAGE_ATTR_REGEX, '')}`);
				})
			).subscribe();
		}

		this.setTheme();

		if (isPlatformBrowser(platformId)) {
			localStorageSvc.storage = localStorage;
		}
	}
Example #15
Source File: local-storage.ts    From ng-conf-2020-workshop with MIT License 5 votes vote down vote up
constructor(@Inject(PLATFORM_ID) platformId: object) {
    if (isPlatformBrowser(platformId)) {
      this.storage = localStorage;
    } else {
      this.storage = new LocalStorageFallback();
    }
  }
Example #16
Source File: product-control.sandbox.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
   * add selected item to cart
   *
   * @param item product detail to be added to cart
   */
  addItemsToCart(item, param) {


    const id: any = item.productId;
    const id_totalOptions: any = param.totalOptions;
    this.productTotal = 0;
    for (let i = 0; i < this.selectedProducts.length; i++) {
      if (
        this.selectedProducts[i].productId === id &&
        this.selectedProducts[i]._totalOptions !== id_totalOptions
      ) {
          if (this.selectedProducts[i].productCount === 1) {
            const tempPrice = +this.selectedProducts[i].price;
            this.productTotal = (this.productTotal + tempPrice).toFixed(2);
        }
      }
    }
    let exists = false;
    this.getSessionData();

    this.selectedProducts = this.selectedProducts.map(_items => {
      if (
        _items.productId === item.productId &&
        _items._totalOptions === id_totalOptions
      ) {
        exists = true;
        if (item.productCount) {
          _items.productCount += item.productCount;
          this.cartTotal += item.productCount;
        } else {
          _items.productCount += 1;
          this.cartTotal += 1;
        }
      }
      return _items;
    });

    if (!exists) {
      this.selectedProducts.push(item);
      if (!item.productCount) {
        item.productCount = 1;
      }
      this.cartTotal += item.productCount;
    }
    this.selectedProducts.forEach(_price => {
      if (
        _price.productId === item.productId &&
        _price._totalOptions === id_totalOptions
      ) {
          const numberPrice: any = +(_price.price);
          let tempPrice = numberPrice + _price._totalOptions;

          tempPrice = tempPrice;
          this.productTotal = (tempPrice * item.productCount) +  this.productTotal;
          this.productTotal = +this.productTotal.toFixed(2);
      }
    });
    const cartParams: any = {};
    cartParams.products = this.selectedProducts;
    cartParams.productTotal = this.cartTotal;
    const availableData: any = {};
    availableData.options = param.totalOptions;
    cartParams.totalPrice = this.productTotal;
    this.snackBar.open(
      'Product ' + item.name + ' is successfully added to cart',
      '×',
      {
        panelClass: 'success',
        verticalPosition: 'top',
        horizontalPosition: 'right',
        duration: 3000
      }
    );
    this.changeCountTotalPrice = cartParams.totalPrice;
    if (isPlatformBrowser(this.platformId)) {
      sessionStorage.setItem(
        'changeCountTotalPrice',
        JSON.stringify(this.changeCountTotalPrice)
      );
    }
    this.HandleCart(cartParams);
  }