所以這是我的問題。我在這裏有這個組件編輯通過輸入傳遞的聯繫人。當我改變輸入文本中的某些內容(雙向數據綁定),然後在點擊保存並路由到另一個組件(顯示所有聯繫人列表)時,此代碼可以工作並更改聯繫人蔘數。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 –