首页 > 解决方案 > 如何在Angular中动态创建子元素并从父组件传递属性

问题描述

我想让我的父 html 文件像:

<div #parent>
<child id="1" [isclicked]="false"></child>
<child id="2"  [isclicked]="false"></child>
<child id="3"  [isclicked]="false"></child>
<child id="4"  [isclicked]="false"></child>
<child id="5"  [isclicked]="false"></child>
<child id="6"  [isclicked]="false"></child>
</div>

但我想从 TS 动态地做到这一点 - 将我所有的孩子都附加到 div #parent

通过在互联网上查看,我发现了类似的东西

@ViewChild('parent', {read: ViewContainerRef})
 parent: ViewContainerRef;
 
 constructor (private componentFactoryResolver: ComponentFactoryResolver) {
 const childComponent = this.componentFactoryResolver.resolveComponentFactory(ChildComponent); 
 const anotherChildComponent = this.componentFactoryResolver.resolveComponentFactory(AnotherChildComponent)
 
 setTimeout(()=>{
 // at this point we want the "child" component to be rendered into the app.component:
  this.parent.createComponent(childComponent);
 },1000);

哪个有效,但我没有找到如何传递我的身份。我相信我需要拥有

Input() id: number
Input() isclicked: boolean

在子 Typescript 中,因为它们是从父级发送的,但我不知道应该在哪里添加代码来绑定isclicked子元素创建中的 id 和“”属性

谢谢

标签: angulardata-bindingparent-childparentcreation

解决方案


这个Angular 指南解释了。基本上你需要做以下事情:

const componentRef = this.parent.createComponent(childComponent);

componentRef.instance.id = someId;
componentRef.instance.isClicked = someIsClicked;

然后在子组件类中有

@Input() id: number;
@Input() isClicked: boolean;

在模板中:

... [isClicked]="isClicked" ...

等等


推荐阅读