如何使用formgroup

时间:2018-07-19 12:18:12

标签: angular post angular-forms

我试图按角度发出发帖请求,但是我发现,如果我使用[formGroup],则不能这样做,因为“提交”按钮什么都不做。我的代码看起来像这样

<form [formGroup]="formGroup" action="https://someUrl.com" method="post">
    <input type="text" name="lang" id="lang" value="en" formControlName = "lang" >
    <input type="submit" >
</form>

如果我删除formGroup模块,它会正常工作。是否有错误,提交覆盖或其他内容?

6 个答案:

答案 0 :(得分:0)

您可以使用ngSubmit指令提交它,

<form (ngSubmit)="onSubmit()" [formGroup]="formGroup" method="post">
    <input type="text" name="lang" id="lang" value="en" formControlName = "lang" >
    <input type="submit" >
</form>

并在组件内部创建 onSubmit 函数

onSubmit(){
   // here you make ajax request using http client
}

答案 1 :(得分:0)

Tadej,在Angular中,通常您会喜欢

<form [formGroup]="formGroup" (submit)="submit(formGroup) >
    <input type="text" name="lang" id="lang" value="en" formControlName = "lang" >
    <input type="submit" >
</form>

//In your .ts
constructor(http:HttpClient){}
submit(formGroup)
{
    if (formGroup.valid)
    {
         this.http.post("https://someUrl.com",formGroup.value).subscribe(res=>{
               //here you received the response of your post
               console.log(res);
               //you can do asomething, like
               alert("datos enviados");
         })
    }
}

答案 2 :(得分:0)

您可以使用如下所示的表单组,以便将表单值提交到后端。

some-item.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';
import { SomeItemService } from './some-item.service';

@Component({
    selector: 'some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.css']
})

export class SomeItemComponent implements OnInit {
 someForm: FormGroup;

 constructor(private someItemService: SomeItemService) { }

 ngOnInit() {
  this.createForm();
 }

 private createForm() {
   this.someForm= new FormGroup({
      field_one: new FormControl(''),
      field_two: new FormControl('')
   });
 }

 submitFunc() {
    this.someItemService.submitForm(this.someForm.value)
                .subscribe(
                    (data) => {
                       console.log('Form submitted successfully');                           
                    },
                    (error: HttpErrorResponse) => {
                        console.log(error);
                    }
                );
        }
 }

}

some-item.component.html

<form [formGroup]="someForm" (ngSubmit)="submitFunc()">
  <input type="text" class="form-control" formControlName="field_one"/>
  <input type="text" class="form-control" formControlName="field_two"/>
  <button type="submit" [disabled] ="!someForm.valid" class="btn btn-success"> Submit </button>
</form>

some-item.service.ts

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class SomeItemService {

 constructor(private http: HttpClient){ }

 submitForm(data): Observable<any> {
   return this.http.post<any>(api-url, data);
 }

}

提交表单后,可以在组件中访问值,并可以通过服务将其传递到后端。我希望这一点现在已经清楚了。

答案 3 :(得分:0)

根据https://angular.io/api/forms/FormControl/#configure-the-control-to-update-on-a-submit-event,您可以设置表单控件以在提交时更新表单组:

searchInput: new FormControl('', { updateOn: 'submit' })

例如:

ngOnInit() {
    this.primarySearch = new FormGroup({
        searchInput: new FormControl('', { updateOn: 'submit' }),
    });
    this.primarySearchSub();
}

primarySearchSub() {
    const primarySearchChange = this.primarySearch.valueChanges;
    primarySearchChange.subscribe(input => {
        console.log(input)
        // Perform your POST here //
    });
}

使用:

<form [formGroup]="primarySearch">
    <mat-form-field>
        <input autocomplete="off" matInput formControlName="searchInput" />
    </mat-form-field>
</form>

答案 4 :(得分:0)

您可以使用常规的html表单行为,但是要使其正常工作,您需要从模块中删除FormsModule,如果您已经在使用FormsModule,则可以创建一个新模块并将新组件放在那里。对我来说,它工作得很好,所以我可以在其他模块中使用FormsModule并使用普通的html表单。

<form action="https://someUrl.com" method="post">
<input type="text" name="lang" id="lang" value="en">
<input type="submit" >
</form>

现在您转到app.module.ts并导入了文件,我从代码中删除了表单组和表单控件

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    **FormsModule**
  ],

如果创建新模块,请确保不包括FormsModule。

答案 5 :(得分:0)

我想使用反应式表单进行初始化和验证,同时仍使用浏览器发布到服务器。这对我有用:

<form class="form-horizontal" [formGroup]="form" >
    <form ngNoForm action="ui-api/setup" method="POST">
        <-- fields -->
        <button type="submit">Submit</button>
        <button type="button" (click)="resetForm()">Reset</button>
    </form>
</form>