所以这是我的问题。我在这里有这个组件编辑通过输入传递的联系人。当我改变输入文本中的某些内容(双向数据绑定),然后在点击保存并路由到另一个组件(显示所有联系人列表)时,此代码可以工作并更改联系人参数。Angular 2无状态或有状态?
import {Component} from 'angular2/core';
import {Contact} from "./contact";
import {Router} from "angular2/src/router/router";
import {OnInit} from "angular2/src/core/linker/interfaces";
import {ContactService} from "./contacts.service";
@Component({
selector:'editor',
template:`
<div class='editor'>
<label>Edit name : </label><input type="text" [(ngModel)]="contact.name">
<br>
<label>Edit email : </label><input type="text" [(ngModel)]="contact.email">
<br>
<label>Edit phone number: </label><input type="text" [(ngModel)]="contact.phone">
<br>
<div class="description">
Description:
<br>
<textarea rows="4" cols="50" [(ngModel)]="contact.description"></textarea>
</div>
<br>
<input type="button" (click)="onCreateContact()" class="button" value="Save Changes"/>
</div>
`,
inputs:["contact"],
styles:[
`
label {
display: inline-block;
width: 145px;
border-left: 3px solid #006ec3;
padding-left: 8px;
padding-bottom: 8px;
}
.description{
border-left: 3px solid #006ec3;
padding-left: 8px;
padding-bottom: 8px;
}
`
]
})
export class ContactEditorComponent implements OnInit{
public contact:Contact;
constructor(private router:Router){
}
onCreateContact(){
this.router.navigate(['Contacts']);
}
}
现在,如果我加入了temp:Contact
变量,它把我接触的克隆,改变临时变量然后将其克隆到联系对象这种方式改变我的课上,变化不再被保存时,我打的按钮。
@Component({
selector:'editor',
template:`
<div class='editor'>
<label>Edit name : </label><input type="text" [(ngModel)]="temp.name">
<br>
<label>Edit email : </label><input type="text" [(ngModel)]="temp.email">
<br>
<label>Edit phone number: </label><input type="text" [(ngModel)]="temp.phone">
<br>
<div class="description">
Description:
<br>
<textarea rows="4" cols="50" [(ngModel)]="temp.description"></textarea>
</div>
<br>
<input type="button" (click)="onCreateContact()" class="button" value="Save Changes"/>
</div>
`,
inputs:["contact"],
styles:[
`
label {
display: inline-block;
width: 145px;
border-left: 3px solid #006ec3;
padding-left: 8px;
padding-bottom: 8px;
}
.description{
border-left: 3px solid #006ec3;
padding-left: 8px;
padding-bottom: 8px;
}
`
]
})
export class ContactEditorComponent implements OnInit{
public contact:Contact;
public temp:Contact;
constructor(private router:Router){
}
onCreateContact(){
this.contact = (<any>Object).assign({}, this.temp);
console.log(this.contact.name);
this.router.navigate(['Contacts']);
}
ngOnInit(){
this.temp = (<any>Object).assign({}, this.contact);
}
}
我所有的通讯录保存在包含联系人的常量数组另一个文件,并通过contact.service访问。
这工作像一个魅力的感谢!所以为了创建我们使用的同一个对象: Object.assign(contact,contact); 而不是 child.contact = Object.assign({},contact); 它只创建对象的新副本。我得到那个权利了吗? –
对象。将第二个对象的所有直接属性分配给第一个对象,并返回第一个。因此,如果您使用Object.assign({},conact),则创建一个新的空对象,然后将联系人的所有属性复制到这个新的空对象。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign –