2016-12-17 67 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

太棒了!非常感謝你的幫助 –