Как проверить правильность ввода формы при отправке в Angular 6 - PullRequest
0 голосов
/ 08 марта 2019

В моем приложении Angular у меня настроены валидаторы форм, но я хочу, чтобы была выполнена валидация форм onSubmit.Поэтому, когда пользователь нажимает кнопку «Отправить», а форма недействительна, появляются ошибки ngIf.Пока мой код:

Component.ts

import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Request } from '../../models/request.model'
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AppComponent } from '../../../app.component';
import { ServicenowService } from '../../services/servicenow.service';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';


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


  public loading = false;

  private customer_id = this.appComponent.customer_id;

  serviceForm;

  u_destination_country = [
    { value: 'Choose an option' },
    { value: 'United Kingdom', },
    { value: 'United States of America', },
    { value: 'Russia', },
    { value: 'Moscow', },
    { value: 'Africa', },
  ];

  users = [
    { id: 'Select an option', },
    { id: '1', },
    { id: '2', },
    { id: '3', },
  ];

  devices = [
    { id: 'Select an option', },
    { id: '1', },
    { id: '2', },
    { id: '3', },
  ];

  constructor(private service: ServicenowService,
    private appComponent: AppComponent,
    private router: Router,
    private http: HttpClient

  ) {
  }

  ngOnInit() {
    this.serviceForm = new FormGroup({
      customer_id: new FormControl(this.customer_id),
      //u_caller_id: new FormControl(this.users[0], Validators.required),
      siebel_id: new FormControl('', Validators.required),
      u_destination_country: new FormControl(this.u_destination_country[0], Validators.required),
      u_phone_number: new FormControl('', Validators.required),
      //u_serial_number: new FormControl(this.devices[0], Validators.required),
      u_short_description: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(5),
        Validators.maxLength(80)
      ])),
      u_message_description: new FormControl('', Validators.required),
    });
  }

  onSubmit() {
    this.http.post("/api/inc",
      this.serviceForm.value,
      {
        headers: new HttpHeaders().set("Content-Type", "application/json")
      }
    ).subscribe((response: any) => {
      console.log(response);//On success response
      this.router.navigate(['/incident/confirmation']);
    }, (errorResponse: any) => {
      console.log(errorResponse);//On unsuccessful response
    });
  }
}

Ответы [ 2 ]

3 голосов
/ 08 марта 2019

Для защиты на уровне шаблона вы можете использовать

<button type="submit" [disabled]="serviceForm.invalid">Submit</submit>
<div class="error" *ngIf="serviceForm.hasError('yourErrorName')">
 Some text
</div>

На уровне компонента это выглядит следующим образом

onSubmit() {
  if(this.serviceForm.invalid) {
    this.serviceForm.setErrors({ ...this.serviceForm.errors, 'yourErrorName': true });
    return;
  }
}
0 голосов
/ 08 марта 2019

Вы можете использовать свойство updateOn , чтобы указать Angular запустить функцию проверки на submit.

Просто добавьте свойство (которое также можно применить к formControl илиa formArray):

this.serviceForm = new FormGroup({
     customer_id: new FormControl(this.customer_id),
         ...
}, { updateOn: 'submit' });

, а также не забудьте защитить функцию отправки:

onSubmit() {
    if (this.serviceForm.valid) {
        ...
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...