提交表单后如何删除NgForm字段

时间:2018-10-03 21:04:23

标签: javascript angular ionic-framework

我想知道是否可以从提交的NgForm函数中删除表单字段。

我正在使用离子3的一个名为Select-Searchable的插件,这两个表单字段正在使用该插件。该插件需要按这样设置阵列,因此它可以正常工作。

我有这个:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ToastController,Platform } from 'ionic-angular';
import { SelectSearchableComponent } from 'ionic-select-searchable';
import { NgForm } from '@angular/forms';
import { Geolocation } from '@ionic-native/geolocation';

import { ReapService } from '../../services/reap-service';
import { ProjectReviewPage } from '../project-review/project-review';

class Location {
  public ID: number;
  public Location: string;
}
class updatedLocation {
  public ID: number;
  public Location: string;
}
@IonicPage()
@Component({
  selector: 'page-project',
  templateUrl: 'project.html',
})
export class ProjectPage {
 private locationsArray: Location[];
 location: Location;
 private updatedLocation: updatedLocation[];
 updatedlocation: updatedLocation; 
 constructor(public navCtrl: NavController,
             public navParams: NavParams,
             public reap: ReapService,
             public toastCtrl: ToastController,
             private geolocation: Geolocation,
             private platform: Platform) {
             
             this.locationsArray = reap.getLocations;
             this.updatedLocation = [];
             }
             
             
   grabLocation(){
        this.selectedClosestLoc = true;
        /* Ensure the platform is ready */
        this.platform.ready().then(() => {
        /* Grabs user geolocation */
        this.geolocation.getCurrentPosition().then((resp) => {
            // 4 decimal places
            this.userLocation = [parseFloat(resp.coords.latitude.toFixed(4)),parseFloat(resp.coords.longitude.toFixed(4))];
           
            this.userLocation = [resp.coords.latitude,resp.coords.longitude];
            //var t0 = performance.now();
            //Calls service to handle location 
            this.reap.grabUserLoc(resp.coords.latitude,resp.coords.longitude);
            //var t1 = performance.now();
            //console.log("Call to grabUserLoc took " + (t1 - t0) + " milliseconds.");
            this.updatedLocation = this.reap.updatedLocation;

            console.log(this.updatedLocation);
          }).catch((error) => {
            //console.log('Error getting location', error);
            this.presentToast(error);
          });
        });
      }          
             
onSubmit(Form: NgForm){
    if(!Form.value.Location){//If user grabs nearest location
      Form.value.Location = Form.value.updatedLocation;//update form value
      //console.log(Form.value.Location);
      Form.value.remove.updatedLocation//Some type of remove option for the form
     }
    }
     searchableChange(event: { component: SelectSearchableComponent, value: any         }) {
        console.log('value:', event.value);
    } 
    resetLocation(){
          this.wellLocation = [];
          this.updatedLocation = [];
          this.selectedClosestLoc = false;
      }
  }

为了使事情更清楚一点,我有一个*ngIf语句,该语句由用户单击以在两个不同的表单字段之间切换的按钮确定。这些字段最终存储了相同的最终值,但是我当然将它们设置为两个不同的值,对于我的API,我觉得保留一个值会更方便。

HTML代码:为简单起见,只显示了问题中的两个表单字段。Location中的数据来自我的API,updatedLocation过滤器根据用户通过gps坐标的位置对数据进行过滤。

 <ion-content>
  <form #f="ngForm" (ngSubmit)="onSubmit(f)">
   <ion-list>  
    <ion-item class="formField ionField" *ngIf="!selectedClosestLoc">
        <ion-label color="primary" stacked >LOCATION</ion-label>
          <select-searchable
          item-content
          [(ngModel)]="location"
          [items]="locationsArray"
          title="Location"
          itemValueField=ID
          itemTextField=Location
          name="Location"
          [canSearch]="true"
          [canClear]="true"
          (onChange)="searchableChange($event)">
        </select-searchable>
    </ion-item>

    <ion-item class="formField ionField" *ngIf="selectedClosestLoc">
      <!-- data thrown into dropdown from API -->
      <ion-label stacked>NEAREST LOCATION</ion-label>
        <select-searchable
         item-content
         ngModel
         title="updatedLocation"
         itemValueField=ID
         itemTextField=Location
         name="updatedLocation"
         [items]="updatedLocation"
         [canSearch]="true"
         [canClear]="true"
         [focusSearchbar]="true"
         (onChange)="searchableChange($event)">
       </select-searchable>
    </ion-item>

     <ion-item>
        <button [disabled]="!f.valid" type="submit" id="submitButton" ion-button            full large>Submit</button>
     </ion-item>
   </ion-list>
  </form>
</ion-content>

2 个答案:

答案 0 :(得分:0)

您可以使用

delete Form.value['updatedLocation'];

除非我误解了原始问题,否则您只关心发送到API的内容,而不是Angular形式。因此,我们只需要从javascript对象中删除属性即可。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

答案 1 :(得分:-1)

Form.reset(); or Form.SetValue(""); or if validators Form.markAsUntouched();

或者如果您尝试从表单组中删除表单控件,则可以使用

 .removeControl();

更多信息,请点击https://angular.io/api/forms/FormGroup