0

我有一个简单的表单,它接受用户输入并将其发布到数据库。

表格如下

import {Component, OnInit} from 'angular2/core';
import {ROUTER_DIRECTIVES} from "angular2/router";
import {HomeComponent} from "../home/HomeComponent";
import {FormBuilder, Validators, ControlGroup} from "angular2/common";


@Component({
    selector: 'profile',
    template: `<h1>Profile Page</h1>
    <form [ngFormModel]="myForm" (ngSubmit)="onSubmit()" #f="ngForm">
    <div>
        <label from="name">Name</label>
        <input [ngFormControl]="myForm.controls['name'] "type="text" id="name" #name="ngForm">
        <span class="validator-error" *ngIf="!name.valid"> required</span>
    </div>
    <button type="submit" [disabled]="!f.valid">submit</button>
    </form>

    <a [routerLink]="['../Dashboard']">Back to Dash</a>

    `,
    directives : [ROUTER_DIRECTIVES]
})

export class ProfileComponent implements OnInit {
    myForm: ControlGroup;

    constructor(private fb: FormBuilder) { }


    onSubmit(form){
       console.log(this.myForm);
       //post to rest API
    }

    ngOnInit():any { 
     this.myForm = this.fb.group({
       'name': ['', Validators.required],
     });
    }
}    

如何在同一组件中显示提交的数据以进行编辑。这个想法是允许用户在提交后编辑数据并在需要时重新提交。

4

1 回答 1

3

我认为有几个不同的步骤:

  1. 使用现有数据填充表单
  2. 提交到后端的同一记录。

您如何填充表单将取决于您的组件是如何加载的。如果您使用路由器加载它,我建议使用记录 id 来获取数据,填充表单,然后您就可以参加比赛了:

routerOnActivate(curr: RouteSegment) {
  let id = curr.getParam('id');
  this.data = this.someDataService.get(id); // return null if id isn't found

  this.myForm = this.fb.group({
    'name': [this.data['name'] || '', Validators.required],
  });
}

从那里开始,约定是您将使用 HTTP PUT 请求提交编辑,因为对现有记录的更新应该是幂等的(创建新记录应该是 POST)。

onSubmit(form) {
  if( this.data ) {
    // this is an edit, so submit with PUT by id
  } else {
    // didn't have initial data, so create a new record with POST
  }
}

如果您没有通过路由加载组件,那么您需要一些东西来将现有数据传递给它。您可以使用服务或 @Input() 字段。

如果您只是希望用户能够在提交后直接编辑他们的数据,那么您实际上不需要做任何特别的事情。您的 submit 方法可以在将数据发送到后端后将数据留在表单中。您只需要您的后端在其对初始 POST 的响应中发送记录的 id,然后让您的提交方法在后续提交时通过该 id 发送 PUT 请求。

给这只猫剥皮的方法肯定不止一种,但希望这能给你一些想法。

于 2016-05-25T03:40:38.650 回答