angular universal: dynamic imports for browser only

Rodion

Is it possible to import a module based on condition? Specificly import external module only if angular 2 universal app being rendered in browser but not in server.

This question is relevant to some PrimeNG modules that depend on browser features and can be rendered only in browser. It would be great to omit them at server rendering cause calendars and other components are not really important for SEO.

Currently I can render Calendar component if turn off server rendering. But server produces an error 'ReferenceError: Event is not defined' in button.js when I include this code below in my app.module.ts and turn on server rendering.

import { CalendarModule } from 'primeng/components/calendar/calendar';
@NgModule({
    ...
    imports: [
        ...,
        CalendarModule
    ]
})

There is a isBrowser condition provided by angular.

import { isBrowser } from 'angular2-universal';

But I don't know how to use it for conditional imports. Is there really a way to do it for modules?

Rodion

So there is a way to render PrimeNG components in browser and omit them while server rendering. Those questions helped me start digging the right direction:

angular-cli: Conditional Imports using an environment variable

How can I conditionally import an ES6 module?

While server rendering I used mock component that renders a simple input field and uses the same selector 'p-calendar'. The final code I ended up with in my app.module.

...//other imports
import { isBrowser } from 'angular2-universal';

let imports = [
    ... //your modules here
];
let declarations = [
    ... //your declarations here
];

if (isBrowser) {
    let CalendarModule = require('primeng/components/calendar/calendar').CalendarModule;
    imports.push(CalendarModule);
}
else {
    let CalendarMockComponent = require('./components/primeng/calendarmock.component').CalendarMockComponent;
    declarations.push(CalendarMockComponent);
}

@NgModule({
    bootstrap: [AppComponent],
    declarations: declarations,
    providers: [
        ... //your providers here
    ],
    imports: imports
})

To make your mock component support [(ngModel)] binding use this tutorial. http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CalendarMockComponent),
    multi: true
};

@Component({
    selector: 'p-calendar',
    template: '<input type="text" class="form-control"/>',
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CalendarMockComponent implements ControlValueAccessor {

    private innerValue: any = '';

    private onTouchedCallback: () => void = () => {};
    private onChangeCallback: (_: any) => void = () => {};

    //From ControlValueAccessor interface
    writeValue(value: any) {
        if (value !== this.innerValue) {
            this.innerValue = value;
        }
    }

    registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }

    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Angular Universal for dynamic content?

Angular 8 Universal Build Failed on SCSS Imports

Angular Universal and browser feature checks

Angular Universal - Only for crawler bots

Firebase Dynamic Links -> universal links only for sub paths

Angular 5 Universal render directly form 'dist' instead of 'browser'

Angular Universal using global browser objects like window and localstorage

Angular Universal - NodeJS Server's Response to HTML for Dynamic Routes

Not able to load @angular/platform-browser-dynamic

Dynamic/lazy imports in Elm

Mixing dynamic imports with if conditions

Host application with dynamic imports

Dynamic Imports - NextJS

Dynamic imports in React

Awaiting on dynamic imports in JavaScript

Angular Universal only showing page source for first page

Angular 4 Universal - Google Analytics / Client Side Only Code

Why are static and dynamic imports in node.js treated differently wrt read-only?

Compile TypeScript file with imports for browser

SSR angular universal and angular 8 - rendering dynamic html content before api completes

Do I need to opt-in to Ivy to use dynamic imports when lazy loading routes (Angular 8)?

How to exclude browser modules from being built in Angular 5 Universal app

@angular/platform-browser vs. @angular/platform-browser-dynamic

Dynamic Imports on ES6

How to use types with dynamic imports?

Dynamic Imports for JavaScript React Meteor

What is the way to use dynamic imports?

Dynamic Page Title for both browser display and Google Analytics in Angular

Imports on angular tests

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive