[英]Create child components in the parent component in Angular
我是Angular&Typescript的新手。 熟悉OOP和Javascript。 我對如何執行以下操作感到困惑:
我想根據parent
組件中的變量在parent
組件中創建並插入許多child
組件實例。 我還想給我從parent
傳遞過來的每個child
組件值。 下面的代碼給我: Uncaught Error: Can't resolve all parameters for ParentComponent: (?, ?).
自從我傳遞了正確數量的參數和正確的類型以來,哪個讓我感到困惑?
Parnet組件:
import { Component, OnInit } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'parent',
template: `
<ul>
<li *ngFor='let child of collOfChildren'>
<child></child>
</li>
</ul>
`
})
export class ParentComponent implements OnInit {
private collOfChildren: Array<ChildComponent> = [];
numOfChildren = 3;
childNames = ['Child 1', 'Child 2','Child 3'];
constructor() {
}
ngOnInit() {
for(let i = 0; i < this.numOfChildren; i++) {
this.collOfChildren.push(new ChildComponent(this.childNames[i],5));
}
}
}
子組件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
private name:String;
private age:number;
constructor(name:String, age:number) {
this.name = name;
this.age = age;
}
ngOnInit() {
}
}
Angular教程有正確的實踐,您不需要初始化子組件數組,只需將子數據傳遞給子組件,如下所示:
<child *ngFor="let childName of childNames" [name]="childName">
並且您需要將輸入裝飾器添加到childComponnet的名稱,如下所示:
@Input() name: string;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.