提交后如何清除表格

时间:2019-04-09 12:43:34

标签: angular

嗨,我正在使用angular7,我的问题是当我想发送表格时他发送了它,而当我重置它时,我有一个验证器验证程序,该验证程序要求在提交后清除我的表格而无需验证必填项

这是我的代码ts:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormArray } from '@angular/forms';
import { FuseTranslationLoaderService } from '@fuse/services/translation-loader.service';
import { AuthService } from 'app/services/auth.service';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { User } from 'app/models/user.model';
import { locale as english } from 'app/pages/dnsaas-access-request/i18n/en'
import { locale as french } from 'app/pages/dnsaas-access-request/i18n/fr'

@Component({
  selector: 'app-dnsaas-access-request',
  templateUrl: './dnsaas-access-request.component.html',
  styleUrls: ['./dnsaas-access-request.component.scss']
})
export class DnsaasAccessRequestComponent implements OnInit {

  form: FormGroup;
  domains: FormArray;
  user: User;
  domainPattern = /^(?!:\/\/)([a-zA-Z0-9-]+\.){0,5}[a-zA-Z0-9-][a-zA-Z0-9-]+\.[a-zA-Z]{2,64}?$/;
  groupPattern = /^[a-zA-Z_]+$/;
  // Private
  private _unsubscribeAll: Subject<any>;

  /**
   * Constructor
   *
   * @param {FormBuilder} _formBuilder
   */
  constructor(
    private _formBuilder: FormBuilder,
    private _fuseTranslationLoaderService: FuseTranslationLoaderService,
    private _authService: AuthService,
    private cdref: ChangeDetectorRef,
    private toastr: ToastrService,
    private spinner: NgxSpinnerService
  ) {
    // Set the private defaults
    this._unsubscribeAll = new Subject();
    this._fuseTranslationLoaderService.loadTranslations(english, french);
  }
  ngAfterContentChecked() {

    this.cdref.detectChanges();

  }
  ngOnInit(): void {
    // Reactive Form
    this.form = this._formBuilder.group({
      firstname: [''],
      lastname: [''],
      email: [''],
      group: ['', Validators.required],
      requested_domains: this._formBuilder.array([this.initItemRows()]),
      comment: ['',],
    });


    this._authService.getAuthStatusListener()
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((user) => {
        this.user = user;
        if (user) {
          this.form.patchValue({
            firstname: user.first_name,
            lastname: user.last_name,
            email: user.user_email
          })
        }

      });
  }

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next();
    this._unsubscribeAll.complete();
  }
  get primaryEmail() {
    return this.form.get('email');
  }

  get requested_domains() {
    return this.form.get('requested_domains');
  }

  get group() {
    return this.form.get('group')
  }

  initItemRows(): FormGroup {
    return this._formBuilder.group({
      domain_name: [''],
      right: ['']
    });

  }

  Send() {
    const request = this.form.value;
    this.spinner.show();
    this._authService.formulaire(request).subscribe(res => {
      this.spinner.hide();
      this.toastr.success("Your form has been successfully sent");
      if(this.form.valid){
        this.form.get('requested_domains').;
        this.form.get('group').reset();
        this.form.get('comment').reset();
      }

    },
      error => {
        this.toastr.error("Your form has not been sent");
        setTimeout(() => {
          /** spinner ends after 5 seconds */
          this.spinner.hide();
        }, 1000);
      }
    );
  }



  addDomains() {
    this.domains = this.form.get('requested_domains') as FormArray;
    this.domains.push(this.initItemRows());
  }

  deleteRow(index: number) {
    this.domains.removeAt(index);
  }

}

这是我的代码HTML:

<div id="forms" class="page-layout simple fullwidth" fxLayout="column">

  <!-- HEADER -->
  <div class="header accent p-24 h-160" fxLayout="row" fxLayoutAlign="start center">
    <div fxLayout="column" fxLayoutAlign="center start">
      <div fxLayout="row" fxLayoutAlign="start center">
        <mat-icon class="secondary-text s-18">home</mat-icon>
        <mat-icon class="secondary-text s-16">chevron_right</mat-icon>
        <span class="secondary-text">{{'contDNS-Acces-Requestact.DNSaaS Access Request' | translate}}</span>
      </div>
      <div class="h1 mt-16">{{'DNS-Acces-Request.DNSaaS Access Request' | translate}}</div>
    </div>
  </div>
  <!-- / HEADER -->
  <div class="content p-24">
    <p class="pt-16 pb-32">
      {{'DNS-Acces-Request.Please fill out the form below to make your request and we will process your request as soon as possible.' | translate}}
    </p>
    <div class="mb-24" fxLayout="column" fxLayoutAlign="center center" fxLayout.gt-md="row">
      <form class="mat-card mat-elevation-z4 p-24 mr-24" fxLayout="column" fxLayoutAlign="start" fxFlex="1 0 auto"
        name="form" [formGroup]="form">

        <div class="" style="text-align: center">
          <img class="logo-ca" src="assets/images/logos/snap.png">
        </div>
        <div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">

          <mat-form-field appearance="outline" fxFlex="50" class="pr-4">
            <mat-label>{{'DNS-Acces-Request.First name' | translate}}</mat-label>
            <input matInput formControlName="firstname" readonly>
            <mat-icon matSuffix class="secondary-text">account_circle</mat-icon>
          </mat-form-field>

          <mat-form-field appearance="outline" fxFlex="50" class="pl-4">
            <mat-label>{{'DNS-Acces-Request.Last name' | translate}}</mat-label>
            <input matInput formControlName="lastname" readonly>
            <mat-icon matSuffix class="secondary-text">account_circle</mat-icon>
          </mat-form-field>

        </div>

        <div fxLayout="row wrap" fxLayoutAlign="start center" fxFlex="1 0 auto">
          <mat-form-field appearance="outline" fxFlex="100" class="pl-4">
            <mat-label>{{'DNS-Acces-Request.Email' | translate}}</mat-label>
            <input matInput formControlName="email" readonly>
            <mat-icon matSuffix class="secondary-text">mail</mat-icon>
          </mat-form-field>
        </div>
        <div fxLayout="row wrap" fxLayoutAlign="start center" fxFlex="1 0 auto">
          <mat-form-field appearance="outline" fxFlex="100" class="pl-4">
            <mat-label>{{'DNS-Acces-Request.AD Group' | translate}}</mat-label>
            <input matInput formControlName="group" [pattern]="groupPattern">
            <mat-icon matSuffix class="secondary-text">group</mat-icon>
            <mat-error *ngIf="group.errors?.required">{{'DNS-Acces-Request.AD Group is required!' | translate}}
            </mat-error>
            <mat-error *ngIf="group.errors?.pattern">{{'DNS-Acces-Request.AD Group is not Valid!' | translate}}
            </mat-error>
          </mat-form-field>
        </div>
        <div formArrayName="requested_domains"
          *ngFor="let domain of form.controls.requested_domains.controls; let i = index" fxLayout="row wrap"
          fxLayoutAlign="start center" fxFlex="1 0 auto">
          <div [formGroupName]="i" fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
            <mat-form-field appearance="outline" fxFlex="40" class="pl-4">
              <mat-label>{{'DNS-Acces-Request.Domain' | translate}}</mat-label>
              <input matInput formControlName="domain_name" required [pattern]="domainPattern">
              <mat-error *ngIf="requested_domains.errors?.required">
                {{'DNS-Acces-Request.Invalid domains!' | translate}}</mat-error>
              <mat-error *ngIf="requested_domains.errors?.pattern">
                {{'DNS-Acces-Request.Invalid domains!' | translate}}</mat-error>
            </mat-form-field>
            <mat-radio-group formControlName="right" aria-label="Select an option" appearance="outline" fxFlex="40"
              class="pl-4" required>
              <mat-radio-button style="font-size : 11px; margin-left: 10px" value="R">
                {{'DNS-Acces-Request.READ' | translate}}</mat-radio-button>
              <mat-radio-button style="font-size : 11px; margin-left: 10px" value="RW">
                {{'DNS-Acces-Request.READ/WRITE' | translate}}</mat-radio-button>
            </mat-radio-group>
          </div>
          <mat-icon title="Ajouter" fxFlex="10" mat-icon-button color="basic" (click)="addDomains()"
            style="color:#3c5d80; cursor: pointer">add_circle</mat-icon>
          <mat-icon *ngIf="form.controls.requested_domains.controls.length > 1" title="Supprimer" fxFlex="10"
            mat-icon-button color="basic" (click)="deleteRow(i)" style="color:#dd2d2d; cursor: pointer">
            delete_forever</mat-icon>

        </div>
        <div fxLayout="row wrap" fxLayoutAlign="start center" fxFlex="1 0 auto">
          <mat-form-field appearance="outline" fxFlex="100" class="pl-4">
            <mat-label>Message</mat-label>
            <textarea matInput formControlName="comment"></textarea>
            <mat-icon matSuffix class="secondary-text">message</mat-icon>
          </mat-form-field>
        </div>
        <div fxLayoutAlign="end center">
          <button mat-raised-button color="primary" [disabled]="form.invalid" (click)="Send()">{{'DNS-Acces-Request.Send'
                    | translate }}</button>
        </div>

      </form>
    </div>
  </div>
  <ngx-spinner bdColor="rgba(51, 51, 51, 0.8)" size="medium" color="#fff" type="ball-clip-rotate"></ngx-spinner>
</div>

这是我提交表单后的表单图片:

enter image description here 这是我的代码,请帮助解决此问题

3 个答案:

答案 0 :(得分:0)

尝试

this.form.controls['input'].reset();// one by one OR this.form.reset();
formDirective.resetForm();

formDirective是FormGroupDirective的实例

答案 1 :(得分:0)

您可以使用clearValidators()清除验证器

this.form.get('group').reset();
this.form.get('comment').reset();

this.form.clearValidators(); // and then call `clearValidators` method

这里是Stackblitz

答案 2 :(得分:0)

由于您要在提交时重设表单,但所有验证程序均未损坏,因此您返回new formGroup并在成功提交后将其分配给form variable

您可以通过以下方式进行操作:

创建一个返回formGroup的函数:

getMyForm(){
    return this._formBuilder.group({
      firstname: [''],
      lastname: [''],
      email: [''],
      group: ['', Validators.required],
      requested_domains: this._formBuilder.array([this.initItemRows()]),
      comment: ['',],
    });
}

您需要做的就是分配this.form=this.getMyForm(),您将拥有一个新实例,其中所有验证程序都保持不变。

 Send() {
    const request = this.form.value;
    this.spinner.show();
    this._authService.formulaire(request).subscribe(res => {
      this.spinner.hide();
      this.toastr.success("Your form has been successfully sent");
      if(this.form.valid){
        this.form = this.getMyForm()
      }

    },
      error => {
        this.toastr.error("Your form has not been sent");
        setTimeout(() => {
          /** spinner ends after 5 seconds */
          this.spinner.hide();
        }, 1000);
      }
    );
  }

您还可以参考下面的stackblitz示例:

https://stackblitz.com/edit/angular-rubcdg