【发布时间】:2017-07-16 06:37:35
【问题描述】:
所以这是我的问题。我在这里有这个组件,它编辑通过输入传递的联系人。此代码有效,当我更改输入文本中的某些内容(双向数据绑定)时,联系人参数会发生更改,然后在点击保存并路由到另一个组件(显示所有联系人列表)时“保存”。
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);
}
}
我所有的联系人都保存在另一个文件中,其中包含一个 Const 联系人数组,并通过 contact.service 访问。
【问题讨论】:
标签: angular stateless stateful