[英]How do I create an Angular2 Component helper that can pass through items from a parent component and use them as if in the same scope?
[英]How can I create child elements dynamically and pass properties for them from the parent component In 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 內部,因為它們是從父級發送的,但我不知道我應該在哪里添加代碼來綁定子元素創建中的 id 和“ isclicked
”屬性
謝謝
這個Angular 指南解釋了。 基本上你需要做以下事情:
const componentRef = this.parent.createComponent(childComponent);
componentRef.instance.id = someId;
componentRef.instance.isClicked = someIsClicked;
然后在子組件 class 中有
@Input() id: number;
@Input() isClicked: boolean;
在模板中:
... [isClicked]="isClicked" ...
等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.