我正在开发一款基于angular 2Ionic应用程序(2.0.0-rc0).所以新推出的ngModules也包括在内.我在下面加上我的app.module.ts..

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { Users } from '../pages/users/users';

@NgModule({
  declarations: [
    MyApp,
    Users
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    Users
  ]
})
export class AppModule {}

entryComponents在这里做什么?在declarations中已经定义了Components.那么,有什么必要重复它们呢?如果这里不包含组件,会发生什么情况?

推荐答案

这适用于使用ViewContainerRef.createComponent()添加的动态添加组件.将它们添加到entryComponents会告诉脱机模板编译器编译它们并为它们创建工厂.

路由配置中注册的组件也会自动添加到entryComponents,因为router-outlet还使用ViewContainerRef.createComponent()将路由组件添加到DOM中.

脱机模板编译器(OTC)只生成实际使用的组件.如果组件没有直接在模板中使用,OTC无法知道是否需要编译它们.使用entryComponents,您可以告诉OTC也编译这些组件,以便它们在运行时可用.

What is an entry component? (angular.io)

NgModule docs (angular.io)

定义定义此组件时也应编译的组件.对于此处列出的每个组件,Angular将创建一个ComponentFactory并将其存储在ComponentFactoryResolver中.

如果没有将动态添加的组件列出到entryComponents,您将收到一条关于缺少工厂的错误消息,因为ANGLE不会创建工厂.

另见第https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

Angular相关问答推荐

Angular 17上的material 工具提示的自定义样式

路由在全局导航中总是给我/甚至使用相对路径

以Angular 动态添加和删除组件形状元素

选中/取消选中-复选框未正确返回TRUE或FALSE

AOS中的数据绑定--可能吗?

PathMatch full始终连接到参数化路径,即使完整路径不匹配也是如此

Angular 17:延迟加载带参数的独立组件?

无法匹配任何路由.URL段:';英雄';

Angular 17-getEnvironment InjectorProviders出现异常

Angular NG5002错误无效的ICU消息和意外字符EOF

在生产模式下使用带Angular 的 livekit

VSCode 调试器空白页面并在使用 VS Code 1.76.1 和 Chrome 111 启动时加载

如何根据响应变化更改 Angular Carousel 的cellsToShow

http 调用的 RxJs 数组

带有Angular 中断的进度条

带有重定向的Angular 2 AuthGuard服务?

清除Angular2中的输入文本字段

如何在 Angular CLI 1.1.1 版中将路由模块添加到现有模块?

如何在 ngFor angular 2 内部使用 track

在渲染视图/模板之前等待 Angular 2 加载/解析模型