我正在使用 Angular2 创建一个简单的 CRUD 应用程序。该应用程序包含一个用于列出当前记录的表格和一个用于提交新记录的表格。提交表格后更新表格以反射(reflect)新记录的正确方法是什么?这是我目前所拥有的。
export class PersonForm {
data: Object;
loading: boolean;
personForm: ControlGroup;
constructor(private _peopleService: PeopleService, personFormBuilder: FormBuilder) {
this.personForm = personFormBuilder.group({
'name': [],
'age': []
});
}
onSubmit(values:any) : void {
console.log(values);
this._peopleService.createPerson(values).subscribe()
}
}
在上面,我假设 .subscribe()
是您处理回调以更新 View 的地方?
这是那个 View :
<h1>People</h1>
<table class="ui celled small table ">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tr *ngFor="#person of people">
<td>
{{person.name}}
</td>
<td>
{{person.age}}
</td>
</tr>
</table>
<div>
<person-form></person-form>
</div>
这是表格:
<form [ngFormModel]="personForm"(ngSubmit)="onSubmit(personForm.value)" class="ui form">
<div class="field">
<label>Full Name</label>
<input id="nameInput" type="text" placeholder="Full Name" [ngFormControl]="personForm.controls['name']">
</div>
<div class="field">
<label>Age</label>
<input id= "ageInput" type="text" placeholder="Age" [ngFormControl]="personForm.controls['age']">
</div>
<button type="submit" class="ui button blue">Submit</button>
</form>
最佳答案
在您的 View 组件中,您需要设置一个事件监听器。我们暂时将其称为 PersonComponent
,因为我不知道您如何调用它。
export class PersonComponent{
person = {};
updatePerson(person){
this.person = person;
}
}
然后在您的 PersonForm
中,您需要设置一个 EventEmitter
export class PersonForm {
data: Object;
loading: boolean;
personUpdated: EventEmitter<any> = new EventEmitter<any>();
...
onSubmit(values:any) : void {
console.log(values);
this._peopleService.createPerson(values).subscribe((person) => {
this.personUpdated.emit(person);
});
}
}
最后,您将订阅 PersonComponent
中的事件,它将监听 personUpdated
事件并使用值运行 updatePerson
方法那个事件。
<person-form (personUpdated)="updatePerson($event)"></person-form>
关于typescript - 提交表单后 Angular2 更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35164879/