angular - 如何在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 和“”属性
谢谢
解决方案
这个Angular 指南解释了。基本上你需要做以下事情:
const componentRef = this.parent.createComponent(childComponent);
componentRef.instance.id = someId;
componentRef.instance.isClicked = someIsClicked;
然后在子组件类中有
@Input() id: number;
@Input() isClicked: boolean;
在模板中:
... [isClicked]="isClicked" ...
等等
推荐阅读
- ubuntu - 在 Ubuntu Server 20.04 中安装后无法访问 Nextcloud Web 界面
- c++ - 了解在不使用乘法运算符的情况下实现 square() 的解决方案
- php - Laravel Livewire 路由不会显示正确的刀片
- python - 反转matplotlib TimedAnimation图中的x刻度标签,而不反转数据?
- python - 亚马逊网络抓取避免机器人检查
- pascal - 帕斯卡在任何地方都使用了吗?
- android - 如何在 TransitionManager 显示的视图上设置 OnClickListener
- audio - FFMPEG 音频流到 icecast 让媒体播放器在每首歌曲后停止
- reactjs - 为什么使用formik useField时不显示错误?
- c# - 我想用 xamarin.forms 获得每帧的当前位置