Angualr6表單提交驗證並跳轉


  在Angular6中,使用NG-ZRROR作為前端開發框架,在進行表單開發時遇到了一些問題,最后解決了,在此記錄。

  

  1.表單構造:

  引入forms:

 

import { FormGroup, FormBuilder, Validators, FormControl, ValidationErrors } from '@angular/forms';

 

 

 

  在form標簽下初始化表單:

  

 <form nz-form [nzLayout]="'inline'" (ngSubmit)="getData()" class="search__form">

 

 

 

  其中 [nzLayout]是初始化布局,(ngSubmit)="getData()" 是事件綁定。

 

  初始化Input組件:

 

 <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>庫位代碼</nz-form-label>
        <nz-form-control [nzSpan]="12" nzHasFeedback>
          <input nz-input formControlName="locationCode" placeholder="庫位代碼">
          <nz-form-explain
            *ngIf="locationForm.get('locationCode').dirty && locationForm.get('locationCode').errors || locationForm.get('locationCode').pending ">
            <ng-container *ngIf="locationForm.get('locationCode').hasError('required')">
              請輸入庫位代碼!
            </ng-container>
            <ng-container *ngIf="locationForm.get('locationCode').hasError('duplicated')">
              庫位代碼不存在!
            </ng-container>
            <ng-container *ngIf="locationForm.get('locationCode').pending">
              正在查詢...
            </ng-container>
          </nz-form-explain>
        </nz-form-control>
      </nz-form-item>

 

  是這個吊樣子的,一個JB輸入框要勞資寫這么多東西。

  nzRequired表示必填項,會在input左邊出現紅色的*,nzHasFeedback是錯誤的小紅叉。

  

 

 

   

 nz-form-explain:

nz-form-explain#

用於顯示提示信息,會自動根據當前的 nzValidateStatus 顯示不同的顏色

注意:每個 nz-form-item 下最多只能有一個 nz-form-explain

nz-form-extra#

用於顯示表單額外提示信息

nz-form-split#

用於顯示分隔符 -

nz-form-text#

nz-form-control 中直接顯示文本

 

   

  2.后端初始化

 

  每一個item里面都會包含一個控制器,formControlName 對應后端構造器中的:

  

//構造器中注入LocationService和Location類
constructor(private fb: FormBuilder, private msg: NzMessageService, private locationService: LocationService, location: Location) {
this.locationForm = this.fb.group({
locationCode: ['', [Validators.required], [this.userNameAsyncValidator]],
locationDesc: ['', [Validators.required]],
Mrp: ['', [Validators.required]],
block: ['', [Validators.required]],
locationType: ['', [Validators.required]],
effective: true,
negativeStock: false,
freeze: false,
});
this.requestBody = location;
}

 

 

 

 

  [Validators.required]表示必填驗證,第三個參數是自定義驗證器。

 

  提交表單需要驗證數據,循環獲取每一個控件的控制器,在進行判斷:

  

  

 
         
  //提交表單
submit(): void {
let isError = false;
for (const i in this.locationForm.controls) {
this.locationForm.controls[i].markAsDirty();
this.locationForm.controls[i].updateValueAndValidity();
if(this.locationForm.controls[i].invalid){
isError = true;
for (const i in this.locationForm.controls) {
this.locationForm.controls[i].markAsDirty();
this.locationForm.controls[i].updateValueAndValidity();
}
break;
}else{
isError = false;
}
}
if(!isError){
this.requestBody.locationCode = this.locationForm.controls['locationCode'].value;
this.requestBody.locationDesc = this.locationForm.controls['locationDesc'].value;
this.requestBody.mrp = this.locationForm.controls['Mrp'].value;
this.requestBody.locationType = this.locationForm.controls['locationType'].value;
this.requestBody.block = this.locationForm.controls['block'].value;
this.requestBody.effective = this.locationForm.controls['effective'].value;
this.requestBody.negativeStock = this.locationForm.controls['negativeStock'].value;
this.requestBody.freeze = this.locationForm.controls['negativeStock'].value;
this.locationService.insertLocation(this.apiUrl, this.requestBody);
}else{
//表單有錯誤
}
}
 

 

 

   在LocationService里面進行請求數據:

  

httpOptions = {
headers: new HttpHeaders(
{
'Content-Type': 'application/json'},
),
};
public insertLocation(url,requestBody): any{
this.http.post(url, requestBody,this.httpOptions).subscribe(
data=>{
console.log(JSON.stringify(data));
this.router.navigateByUrl("location")
},
error1 => {
console.log(JSON.stringify(error1));
}
)
}
 

 

 

  將對象傳入,加入請求頭,就ok了。

 

  SpringBoot后端接收。

  

 
         
@RestController
@RequestMapping("/location")
@Api(tags = "庫位", value = "TEST")
public class LocationController {

private Gson gson = new Gson();

@Resource
private LocationDao locationDao;

@ApiOperation(value = "添加庫位信息", notes = "添加一個庫位")
@PostMapping("/insertLocation")
public @ResponseBody
String insertLocation(@RequestBody Location location) {

System.out.println("[LOCATION]:"+location);
location.setId(0);
location.setFactory("PO1");
location.setMrpFactory("P01A");
locationDao.insert(location);
return gson.toJson(new RestMessage("success","400",null));
}
 

 

 

 

  為Demo版,比較隨意。

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM