我在angular2中构建基本Todo应用程序,当我单击添加按钮以使用输入从父级向子级发送数据时我得到没有提供者的字符串! (child-> string),并且没有显示数据只显示子类的按钮,这是什么意思
这是父组件:
@Component({
selector : 'parent-component',
directives : [child],
template : `
<h1 class= "text-center">ToDo App</h1>
<div class = "form-group">
<lable>Task</lable>
<input type = "text" class = "form-control" #task>
<lable>Detail</lable>
<input type = "text" class = "form-control" #detail >
<button type = "submit" class = "btn btn-default"
(click) = "addtask(task, detail)">Add Task</button>
<child-component *ngFor = "#todo of Array" [taskobject] = "todo">
Loading... </child-component>
</div>
`
})
class parent{
//taskobj : {task : string, details : string, id: number};
Array : child[];
id : number;
constructor(){
//i want this to initialize asa parent create
this.Array = [];
}
addtask(task : HTMLInputElement, detail : HTMLInputElement){
// this.taskobj.task= task.value;
// this.taskobj.details = detail.value;
this.id = Date.now();
// this.array.push();
this.Array.push(new child(task.value, detail.value, this.id ));
console.log(Array)
task.value = '';
detail.value = '';
}
这是儿童组成部分:
@Component({
selector : 'child-component',
inputs : ['taskobject'],
//outputs : ['objectsend'],
template : `
{{taskobject.task}}
{{taskobject.details}}
<button type = "button" class = "btn btn-default"
(click) = "deletetask()">Delete</button>
<button type = "button" class = "btn btn-defualt"
(click) = "updatetask()">Update</button>
`
})
class child{
//we are creating a instance just as configured as child component
task : string;
detals : string;
id : number;
//array : any[];
constructor(task : string, detail : string, id : number){
this.task = task;
this.detals = detail;
this.id = id;
}
}
2 回答
你得到一个错误,因为Angular2自己实例化
child
类,并尝试在其构造函数级别注入你定义的参数 . 他们没有相关的提供者......否则,如果要引用父组件中的子组件,可以利用
@ViewChild
装饰器通过注入从父组件引用子组件:这是更新的plunkr:http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview .
您可以注意到,也可以使用
@Query
参数装饰器:希望它对你有帮助,蒂埃里
构造函数参数从
bootstrap(AppComponent, [SomeProvider, SomeOtherProvider, ...]);
中指定的DI提供程序解析输入是自动分配的,但仅在生命周期调用
ngOnInit()
之后 .