【问题标题】:Angular 2 - get child component to load inside parent component(getting created dynamically)Angular 2 - 让子组件加载到父组件内(动态创建)
【发布时间】:2017-01-10 09:22:51
【问题描述】:

我正在尝试动态创建一个标题,构建标题模板并将其作为“字符串”传递给我的动态组件。我的要求是在头组件模板字符串中调用另一个组件并加载它。

已在此处为该场景创建了一个有效的 Plunker

我在浏览器控制台中收到错误消息:

Unhandled Promise rejection: Template parse errors:
'alert' is not a known element:
1. If 'alert' is an Angular component, then verify that it is part of this module.
2. If 'alert' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("     <span class="title" style="float: right; margin-right: 10px;">
                                [ERROR ->]<alert></alert>   
                                <img class="notify-circle" src="https://cdn0.iconf"): DynamicComponent@2:32 ; Zone: <root> ; Task: Promise.then ; Value: Object { _nativeError: Error, stack: "" } BaseError@https://unpkg.com/@angular/compiler/bundles/compiler.umd.js:1595:29 [angular]

问题:

如何使用选择器'&lt;alert&gt;&lt;/alert&gt;' 在构造为字符串的标题模板中识别“警报”组件。

这个概念可能看起来很奇怪,但要求就是这样。

【问题讨论】:

  • @yurzui..thanks.. 完美满足我的要求.. 将在我的许多类似情况下有所帮助。您可以发布您的答案以供接受。

标签: angular


【解决方案1】:

您可以创建特殊的共享模块,始终包含您需要的内容

@NgModule({
  declarations: [AlertComponent],
  exports: [AlertComponent]
})
export class SharedDynamicModule {}

然后将其导入您的DynamicModule

dynamic.ts

@NgModule({
  imports: [ CommonModule, SharedDynamicModule ],
  declarations: [ DynamicComponent ]
})
class DynamicHtmlModule { }

Modified Plunker

【讨论】:

  • @yurzui..只是有点好奇,如果未来需要动态创建警报组件,共享模块肯定不会在那种情况下工作(只是编辑了问题中的 plunker 并看到了)。 .是否甚至可以动态创建警报和标题并在布局上呈现它。
  • 请在plunker上转载
  • 这里是带有场景的更新 plunker..link,已删除警报组件并在 header 中动态创建它,但问题是没有任何 selector/viewContainerRef ,我们如何在 header 中调用 alert 以便在动态加载 header 时将 alert 作为其创建的子组件。跨度>
  • 每次调用 this.cmpRef.destroy()this.vcRef.clear(); 都会破坏动态创建的组件 AOT 不支持编译器。
  • 您在 cmets 中提出的问题看起来像是其他问题。如果你想这样做,我认为你的项目架构非常糟糕。 Angular 团队完全反对使用 Compiler
猜你喜欢
  • 2017-12-03
  • 2022-07-21
  • 2017-11-20
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 2017-02-24
相关资源
最近更新 更多