我在使用angular2中的ngFor指令时遇到了生成组件的问题。
我想要的组件模型树是: RootComponent ArticlesComponent 第1条 Article_2 Article_N
**RootComponent.html**
<section>Html for root component goes here</section>
<articles>This contains the articles html and will act as container for enumerated article tags</articles>
**Articles.component.ts**
import {Component} from "@angular/core";
import {ArticleComponent} from "./article.component";
@Component({
moduleId : module.id,
selector : 'articles-list',
template : `<div class="row">
<ul>
<li *ngFor="let article of articles" >
<article [title]="article.title"
[link]="article.link"></article>
</li>
</ul>
</div>`
})
export class ArticleListComponent{
public articles :ArticleComponent[];
constructor(){
this.articles = [];
let articleObj1 = new ArticleComponent("title1","link1");
let articleObj2 = new ArticleComponent("title2","link2");
this.articles.push(articleObj1);
this.articles.push(articleObj2);
}
}
**Article.component.ts**
import {Component,Input} from "@angular/core";
@Component({
moduleId: module.id,
selector: 'article',
templateUrl: `<div class ="row">
<h3>{{title}}</h3>
<h5><a href="#" >{{link}}</a></h5>
</div>`
})
export class ArticleComponent {
@Input() title : string;
@Input() link : string;
public count:number;
constructor(title,link){
this.title = title;
this.link = link;
}
incrementCount(){
this.count++;
}
}
System.js会抛出错误:
(SystemJS) Can't resolve all parameters for ArticleComponent: (?, ?).↵ Error: Can't resolve all parameters for ArticleComponent: (?, ?).↵
这个错误究竟意味着什么以及如何纠正这个错误?
答案 0 :(得分:1)
ArticleComponent
由Angulars DI实例化。如果它有参数,它们需要由DI解析。 title
和link
无法解析,因为没有提供商。没有类型注释的参数也需要@Injectable()
装饰器。
我认为正确的方法是从构造函数中删除参数,而只使用输入。
export class ArticleComponent {
@Input() title : string;
@Input() link : string;
public count:number;
/*constructor(title,link){
this.title = title;
this.link = link;
}*/
incrementCount(){
this.count++;
}
}
也可以缩短ArticleListComponent
中的构造函数,因为如上所述,DI会创建组件实例。
export class ArticleListComponent{
public articles :ArticleComponent[];
/*
constructor(){
this.articles = [];
let articleObj1 = new ArticleComponent("title1","link1");
let articleObj2 = new ArticleComponent("title2","link2");
this.articles.push(articleObj1);
this.articles.push(articleObj2);
}*/
}
您需要的只是*ngFor
的数据,其余部分由<article>
export class ArticleListComponent{
public articles :ArticleComponent[];
constructor(){
this.articles = [{title: "title1",link: "link1"}, {title: "title2",link: "link2"}];
}
}
答案 1 :(得分:0)
根据您的代码,只需更改
即可let articleObj1 = {"title":"title1","link" : "link1"};
let articleObj2 = {"title":"title2","link" : "link2"};
你会得到所需的输出。
没有必要这样做:
let articleObj1 = new ArticleComponent("title1","link1");
let articleObj2 = new ArticleComponent("title2","link2");
错误与ArticleComponent("title1","link1")
有关,您的ArticleComponent
在构造函数中没有这两个参数。