我研究了角度2,我遇到了问题。
实际上,实际上,我将每个组件属性传递给模板,如下所示:
import {Component, bootstrap, NgFor,NgModel} from 'angular2/angular2';
import {TodoItem} from '../item/todoItem';
@Component({
selector: 'todo-list',
providers: [],
templateUrl: 'app/todo/list/todoList.html',
directives: [NgFor,TodoItem,NgModel],
pipes: [],
styleUrls:['app/todo/list/todoList.css']
})
export class TodoList {
list:Array<Object>;
constructor(){
this.list = [
{title:"Text 1", state:false},
{title:"Text 2", state:true}
];
}
}
<todo-item [title]="item.title" [state]="item.state" *ng-for="#item of list"></todo-item>
import {Component, bootstrap, Input} from 'angular2/angular2';
@Component({
selector: 'todo-item',
providers: [],
templateUrl: 'app/todo/item/todoItem.html',
directives: [],
pipes: [],
styleUrls:['app/todo/item/todoItem.css']
})
export class TodoItem {
@Input()
title:String;
@Input()
state:Boolean;
}
我想知道是否可以通过传递每个属性直接在模板内部传递完整对象?
<todo-item [fullObj]="item" *ng-for="#item of list"></todo-item>
答案 0 :(得分:23)
是的,将整个对象作为属性传递是完全正确的。
语法相同,因此只需为整个对象创建一个属性。
%9[^\n]
以下是一个示例:http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0
答案 1 :(得分:8)
这样做没有问题。您可以选择两种语法:
@Component({
selector: 'my-component',
inputs: ['item: item']
})
export class TodoItem {
item: { title: string, state: boolean };
}
或
@Component({
selector: 'my-component'
})
export class TodoItem {
@Input() item: { title: string, state: boolean };
}
和绑定:
<todo-item [item]="item" *ng-for="#item of list"></todo-item>
您需要考虑的事情,就是当以这种方式传递对象时,您传递引用该对象。这意味着您对“child”组件中对象所做的任何更改都将反映在“父”Component对象中:
export class TodoItem implements OnInit {
ngOnInit() {
//This is modifying the object in "parent" Component,
//as "this.item" holds a reference to the same "parent" object
this.item.title = "Modified title";
}
}
例外情况是指定其他对象。在这种情况下,它不会反映在“父”组件中,因为它不再是相同的对象引用:
export class TodoItem implements OnInit {
ngOnInit() {
//This will not modify the object in "parent" Component,
//as "this.item" is no longer holding the same object reference as the parent
this.item = {
title: 'My new title',
state: false
};
}
}