gpt4 book ai didi

javascript - Angular 2 : Creating child components programmatically

转载 作者:IT王子 更新时间:2023-10-29 03:11:40 24 4
gpt4 key购买 nike

问题

如何使用 Angular2 在父组件内创建子组件并在 View 中显示它们?如何确保注入(inject)物正确注入(inject)到子组件中?

例子

import {Component, View, bootstrap} from 'angular2/angular2';
import {ChildComponent} from './ChildComponent';

@Component({
selector: 'parent'
})
@View({
template: `
<div>
<h1>the children:</h1>
<!-- ??? three child views shall be inserted here ??? -->
</div>`,
directives: [ChildComponent]
})
class ParentComponent {

children: ChildComponent[];

constructor() {
// when creating the children, their constructors
// shall still be called with the injectables.
// E.g. constructor(childName:string, additionalInjectable:SomeInjectable)
children.push(new ChildComponent("Child A"));
children.push(new ChildComponent("Child B"));
children.push(new ChildComponent("Child C"));
// How to create the components correctly?
}
}
bootstrap(ParentComponent);

编辑

我在 API docs preview 中找到了 DynamicComponentLoader .但是在执行示例时出现以下错误:元素 0 处没有动态组件指令

最佳答案

这通常不是我会采用的方法。相反,我会依赖于一个数组的数据绑定(bind),当对象被添加到支持数组时,该数组将渲染出更多的子组件。本质上是包裹在 ng-for 中的子组件

我这里有一个类似的例子,它呈现了一个动态的子列表。不是 100% 相同,但似乎概念仍然相同:

http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

关于javascript - Angular 2 : Creating child components programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com