2016-12-17 69 views
13

我在我的angular 2工程中有一个窗体。如何获取Angular 2中的表单数据

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

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

帮助将不胜感激。由于

+0

检查此链接... http://stackoverflow.com/questions/41154319/how-to-post-json-object-with-http-post-angular-2-php-server-side –

+0

@AmitSuhag,我想知道如何通过点击事件和onSubmit方法来绑定表单数据。然后如何将它串联起来。你能帮我整个解决方案...这将是对我非常有帮助... –

回答

22

在角2+我们处理的方式有两种:

  • 模板驱动

我在这里简单的模板驱动的形式共享代码。如果你想要做的使用反应形式,然后检查此链接它:Angular2 reactive form confirm equality of values

你的模块文件应该有这些:

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) 

进行简单的注册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> 

现在你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. 
    } 
} 

要处理这些数据在服务器端使用此链接:How to post json object with Http.post (Angular 2) (php server side)。我认为这已经足够了。

+0

太棒了!非常感谢你的帮助 –