Angular 5默认表单提交

时间:2018-03-13 18:08:32

标签: angular angular5

您好有办法执行默认提交连接到表单模型的表单吗?。

  <form action="http://someaction.com" [formGroup]="SendForm" method="POST">
    <input name="currency" formControlName="sendCurrency">
    <input name="amount" formControlName="sendPrice">

    <fieldset *ngFor="let item of SendData; let i = index">
        <input name="vouchers[{{i}}][quantity]" value="{{item.count}}">
        <input name="vouchers[{{i}}][ean]" value="{{item.code}}">
    </fieldset>

    <input type="submit" value="submit">

  </form>

**更新** 我需要像下面的表格一样充分发挥行为。因此,在提交用POST数据重定向用户之后。

<form action="http://someurl.com" method="POST" >
   <input type="submit" value="asd">
</form>

3 个答案:

答案 0 :(得分:1)

根据您的修改,这是您需要做的事情的基础。您必须弄清楚其余的业务逻辑,因为我不了解您的所有要求。

// In your **.component.ts file:
export class MyClass {
  public formGroup;
  
  constructor(private readonly httpClient: HttpClient, /* ...rest of your injections */) {
    // Rest of your constructor function here.
  }
  
  // The rest of your code here.
  
  public onSubmit(): void {
    this.httpClient.post('https://yourUrl.com/my/path', this.formGroup.getRawValue())
      .subscribe(
        (val) => console.log(val),
        (err) => console.error(err)
      );
  }
}
<form action="http://someaction.com" [formGroup]="SendForm" method="POST" (ngSubmit)="onSubmit()">

答案 1 :(得分:1)

使用ngNoForm属性as documented。这样可以防止所有“不可思议的” Angular行为,并且您将能够以本机方式提交表单(并重新加载页面)。

类似于以下内容:

<form ngNoForm action="http://someurl.com" method="POST" >
   <input type="submit" value="asd">
</form>

答案 2 :(得分:0)

  

(用AJAX提交角表)并且您的html表单应该被

<form method="post" id="query">
<div [formGroup]="queryForm">
<ion-list no-line>
  <ion-card>
    <ion-card-header >Query Details</ion-card-header>
    <ion-card-content>
      <ion-item>
        <ion-label floating>Your Name</ion-label>
        <ion-input type="text" name="name" formControlName="name" id="name" ></ion-input>
      </ion-item>
      <div class="validation-errors">
        <ng-container *ngFor="let validation of validation_messages.field_name; let i=index">
          <div class="error-message" *ngIf="i==0 && queryForm.get('name').hasError(validation.type) && (queryForm.get('name').dirty || queryForm.get('name').touched)">
            Your Name {{ validation.message }}
          </div>
        </ng-container>
      </div>
      <ion-item>
        <ion-label floating>Phone</ion-label>
        <ion-input type="text" name="phone" formControlName="phone" id="phone" ></ion-input>
      </ion-item>
      <div class="validation-errors">
        <ng-container *ngFor="let validation of validation_messages.field_name">
          <div class="error-message" *ngIf="queryForm.get('phone').hasError(validation.type) && (queryForm.get('phone').dirty || queryForm.get('phone').touched)">
            Phone number {{ validation.message }} {{ validation.type=='maxlength'?queryForm.get('mobile').errors.maxlength.requiredLength:'' }} 
          </div>
        </ng-container>
      </div>
      <ion-item>
        <ion-label floating>Email</ion-label>
        <ion-input type="text" name="email" formControlName="email" id="email" ></ion-input>
      </ion-item>
      <div class="validation-errors">
        <ng-container *ngFor="let validation of validation_messages.field_name">

          <div class="error-message" *ngIf="queryForm.get('email').hasError(validation.type) && (queryForm.get('email').dirty || queryForm.get('email').touched)">
            Email {{ validation.message }}
          </div>
        </ng-container>
      </div>
      <ion-item>
        <ion-label floating>Subject</ion-label>
        <ion-input type="text" name="subject" formControlName="subject" id="subject" ></ion-input>
      </ion-item>
      <div class="validation-errors">
        <ng-container *ngFor="let validation of validation_messages.field_name; let i=index">
          <div class="error-message" *ngIf="i==0 && queryForm.get('subject').hasError(validation.type) && (queryForm.get('subject').dirty || queryForm.get('subject').touched)">
            Subject {{ validation.message }}
          </div>
        </ng-container>
      </div>
      <ion-item>
          <ion-label floating>Message</ion-label>
        <ion-textarea type="text" name="message" formControlName="message" id="message" placeholder=""></ion-textarea>
      </ion-item>
      <div class="validation-errors">
        <ng-container *ngFor="let validation of validation_messages.field_name; let i=index">
          <div class="error-message" *ngIf="i==0 && queryForm.get('message').hasError(validation.type) && (queryForm.get('message').dirty || queryForm.get('message').touched)">
            Message {{ validation.message }}
          </div>
        </ng-container>
      </div>
    </ion-card-content>
  </ion-card>
</ion-list>
</div>
<div padding>
  <button ion-button block large  name="submit" [disabled]="!queryForm.valid" id="submit" (click)="this.sendQuery()">Submit</button>
</div>

  

您必须在下面导入所有这些内容

import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController, AlertController, Platform, DateTime } from 'ionic-angular';
import{ Validators, FormBuilder, FormGroup, FormControl, ValidatorFn, AbstractControl }from'@angular/forms';
  

组件注入器   @零件({     选择器:“页面查询”,     templateUrl:'query.html',   })   您必须在类中声明所有该变量。验证码:任何; captcha_text:any; validate_messages:any; queryForm:FormGroup;

     

您的构造函数将是这样

构造函数(公共navCtrl:NavController,公共navParams:NavParams,公共loadingCtrl:LoadingController,公共平台:平台,公共splashScreen:SplashScreen,公共sharedService:SharedService,公共alertCtrl:AlertController,公共formBuilder:FormBuilder)

  

然后将进行表单验证

this.queryForm = this.formBuilder.group({         名称:new FormControl('',Validators.required),         电话:new FormControl('',Validators.compose([Validators.required,numberValidator,Validators.maxLength(14)])),         email:new FormControl('',Validators.compose([Validators.required,Validators.email])),         subject:new FormControl('',Validators.required),         消息:新的FormControl('',Validators.required)       });

  this.validation_messages = {'field_name': [
    { type: 'required', message: ' is required' },
    { type: 'email', message: ' is invalid' },
    { type: 'minlength', message: ' can\'t be less than ' },
    { type: 'maxlength', message: ' can\'t be more than ' },
    { type: 'numbervalidator', message: ' must contain only number' },
   ]};
 function numberValidator(control: FormControl) {
  let userInput = control.value;
  if (/^[0-9]*$/.test(userInput) == false) {
    return {
      numbervalidator: {
        valid: false
      }
    }
  }
  return null;
}
  

发送查询函数send_query()将如下所示

sendQuery = ()=>{
this.sharedService.startAnalytics('Send Query','Submit');
var postdata=$('#query').serialize() ;
var c=$('#query').serialize().split("=");
var cap=c[c.length-1];
console.log(cap)
$.ajax({
  url: this.sharedService.basePath+'/api/v1/sendquery/',
  type: "POST",
  dataType: "json",
  data:postdata,
  async: true,
  success: (data)=> {
    this.presentAlert('Send Query',data[0]['msg']);

      console.log(data)
      if(data[0]['type']!='warning'){
        this.navCtrl.pop();
      }
    }
})

}