是否可以根据条件导入模块?仅当 angular 2 通用应用程序在浏览器中呈现但不在服务器中呈现时,才专门导入外部模块。

这个问题与一些依赖浏览器功能的 PrimeNG 模块有关,并且只能在浏览器中呈现。在服务器渲染时省略它们会很棒,因为日历和其他组件对于 SEO 来说并不重要。

目前,如果关闭服务器渲染,我可以渲染 Calendar 组件。但是,当我在 app.module.ts 中包含以下代码并打开服务器呈现时,服务器会在 button.js 中产生错误“ReferenceError: Event is not defined”。

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


angular 提供了一个 isBrowser 条件。

import { isBrowser } from 'angular2-universal';


但我不知道如何将它用于条件导入。真的有办法为模块做到这一点吗?

最佳答案

因此,有一种方法可以在浏览器中渲染PrimeNG组件,并在服务器渲染时忽略它们。这些问题帮助我开始寻找正确的方向:

angular-cli: Conditional Imports using an environment variable

How can I conditionally import an ES6 module?

在服务器渲染时,我使用了模拟组件,该组件渲染一个简单的输入字段并使用相同的选择器“p-calendar”。我最终在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
})


为了使您的模拟组件支持[(ngModel)]绑定(bind),请使用本教程。
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;
    }
}

关于 Angular 通用 : dynamic imports for browser only,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40751383/

10-11 22:25
查看更多