Tho*_*mas 18 typescript angular
我研究角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;
}
Run Code Online (Sandbox Code Playgroud)
我想知道我是否可以通过传递每个属性直接传递模板内的完整对象?
<todo-item [fullObj]="item" *ng-for="#item of list"></todo-item>
Run Code Online (Sandbox Code Playgroud)
TGH*_*TGH 23
是的,将整个对象作为属性传递是完全正确的.
语法是相同的,所以只需为整个对象创建一个属性.
@Component({
selector: 'my-component'
})
export class MyComponent{
@Input() item;
}
<my-component [item]=item></my-component>
Run Code Online (Sandbox Code Playgroud)
这是一个例子:http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0
这样做没有问题.您可以选择以下两种语法:
@Component({
selector: 'my-component',
inputs: ['item: item']
})
export class TodoItem {
item: { title: string, state: boolean };
}
Run Code Online (Sandbox Code Playgroud)
要么
@Component({
selector: 'my-component'
})
export class TodoItem {
@Input() item: { title: string, state: boolean };
}
Run Code Online (Sandbox Code Playgroud)
和绑定:
<todo-item [item]="item" *ng-for="#item of list"></todo-item>
Run Code Online (Sandbox Code Playgroud)
但是,您需要注意的是,当以这种方式传递对象时,您将传递对该对象的引用.这意味着您对"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";
}
}
Run Code Online (Sandbox Code Playgroud)
例外情况是,如果您指定了其他对象.在这种情况下,它不会反映在"父"组件中,因为它不再是相同的对象引用:
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
};
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45787 次 |
| 最近记录: |