【发布时间】:2020-03-12 01:34:48
【问题描述】:
我希望通过不同子组件的 html 进行父视图循环。我正在使用 Angular8。我该怎么做?
我已经尝试过使用 ViewChildren 的各种尝试,例如建议的 here 和 here。
但 ViewChildren 的这些和其他示例似乎与我的想法不同。也可能是我对 ViewChildren 缺乏了解。
这里有一些伪代码来表达我的想法(我知道它不起作用,但希望它在这里阐明了目标):
*happy-parent-component:
html:
<div *ngFor="let childComponent of childComponents" >
<{{childComponent}} ></{{childComponent}}> <!--I understand this doesn't work-->
</div>
ts:
import { ChildComponent1} from '../child-component1/child-component1.component"
import { ChildComponent2} from '../child-component2/child-component2.component"
...
export class HappyParentComponent implements OnInit {
@ViewChild(ChildComponent1, {static: false})
@ViewChild(ChildComponent2, {static: false})
public childComponents = [ChildComponent1, ChildComponent2] //(I understand this doesn't work...)
*子组件1:
html:
<div><!--fancy html from childcomponent1 --></div>
*子组件2:
html:
<div><!--fancy html from childcomponent2 --></div>
HappyParentComponent 视图上的结果是:
<!--fancy html from childcomponent1 -->
<!--fancy html from childcomponent2 -->
有没有办法做到这一点?
编辑: 只是为了了解更多信息,我想动态添加子组件的 html,而不是直接将 childComponen1、childComponent2 等放入父视图 html 的原因是将显示哪些组件取决于用户选择。
所以用户会做出某些选择,这会改变显示的子组件。随着时间的推移,最终可能会有很多子组件。
【问题讨论】:
-
所以你基本上想在你的html中动态插入组件?您试图解决的问题是什么导致您认为这可能是解决方案?为什么不直接把
<app-child-1></app-child-1> <app-child-2></app-child-2>放在那里? -
谢谢,是的,我想动态插入组件。不只是将 app-child-1 和 app-child 2 等直接放入 html 的原因是,将添加哪些组件实际上取决于用户的选择。根据他们选择的选项,将显示不同的子组件。
标签: angular