我对Angular& amp;打字稿。熟悉OOP&的JavaScript。我对如何执行以下操作感到困惑:
我想在child
组件中创建和插入一些parent
组件实例,具体取决于parent
组件中的变量。我还想提供从child
传递的每个parent
组件值。下面的代码给了我:
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() {
}
}
答案 0 :(得分:0)
Angular教程有正确的做法,你不需要初始化子组件数组,你只需要将子数据传递给子组件,如下所示:
<child *ngFor="let childName of childNames" [name]="childName">
您需要将输入装饰器添加到childComponnet的名称中,如下所示:
@Input() name: string;