如何在Angular 2中获取表单数据

Dee*_*ain 21 angular2-forms angular2-services angular

我的角度2项目中有一个表格.

我知道如何从API中检索数据.但是不知道如何在那里执行CRUD操作.

任何人都可以帮我解决如何以JSON格式将表单数据发送到PHP /任何其他语言的Web服务的简单代码...

帮助将不胜感激.谢谢

Ami*_*mar 35

在Angular 2+中,我们处理表单有两种方式:

  • 模板驱动的
  • 反应

在这里,我将共享简单模板驱动表单的代码.如果您想使用反应形式,请检查此链接:Angular2反应形式确认值的相等性

您的模块文件应具有以下内容:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { MyApp } from './components'

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [MyApp],
  bootstrap: [MyApp]
})
export class MyAppModule {

}

platformBrowserDynamic().bootstrapModule(MyAppModule)
Run Code Online (Sandbox Code Playgroud)

简单注册html文件:

<form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
  <label for="email">Email</label>
  <input type="text" name="email" id="email" ngModel>

  <label for="password">Password</label>
  <input type="password" name="password" id="password" ngModel>

  <button type="submit">Sign Up</button>
</form>
Run Code Online (Sandbox Code Playgroud)

现在你的registration.ts文件应该是这样的:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'register-form',
  templateUrl: 'app/register-form.component.html',
})
export class RegisterForm {
  registerUser(form: NgForm) {
    console.log(form.value);
    // {email: '...', password: '...'}
    // ... <-- now use JSON.stringify() to convert form values to json.
  }
}
Run Code Online (Sandbox Code Playgroud)

要在服务器端处理此数据,请使用以下链接:如何使用Http.post(Angular 2)(php服务器端)发布json对象.我认为这已经足够了.