【问题标题】:Error message not showing in a reactive form错误消息未以反应形式显示
【发布时间】:2021-12-03 21:36:25
【问题描述】:

我有一个包含三个错误消息的反应式表单,但是当我在文本框上输入内容时没有出现错误,我正在寻找丢失或输入错误的内容,但我看不到任何内容。任何帮助将不胜感激。 角度版本:12.2.10

Ts 文件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators, FormControl} from '@angular/forms';
import { ServicioSettings } from '../data/servicio-settings';
import { DataService } from '../data/data.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


@Component({
  selector: 'app-verhoras',
  templateUrl: './verhoras.component.html',
  styleUrls: ['./verhoras.component.css']
})
export class VerhorasComponent implements OnInit {

  servicioSettings: ServicioSettings = {
    IdTecnico: null,
    tecnico: null,
    servicioRealizado: null,
    fechaDeInicio: null,
    horaDeInicio: null,
    semanaDelAno: null,    
    fechaDeFinalizacion: null,
    horaDeFinalizacion: null,
    cantidadDeHoras: null,
    tipoDeHora: null
  };

  myForm: FormGroup;  
  items: ServicioSettings;
  submitted = false;

   constructor(private formBuilder: FormBuilder, private dataService: DataService)  {   }       

    iniciarFormulario(){      
      this.myForm = new FormGroup({        
        IdTecnico: new FormControl(this.servicioSettings.IdTecnico, [Validators.required, Validators.minLength(4), Validators.maxLength(30)]),        
        semanaDelAno: new FormControl(this.servicioSettings.semanaDelAno,[Validators.required])       
      });     
   }

  ngOnInit(): void {
    this.iniciarFormulario();
  }

  onSubmit() {
    this.submitted = true;

    if (this.myForm.valid) {
        console.log(this.myForm.value)
        this.dataService.getServicioSettingsForm(this.myForm.value).subscribe(
            //result => console.log('success ', result),
            result => this.items = result,
            error => console.log('error ', error)
        );
    }

  }
}

HTML 文件:

<form (ngSubmit)="onSubmit()" [formGroup]="myForm">
  <div class="form-group">
    <label for="IdTecnico">Id técnico (*)</label>
    <input type="number" class="form-control" id="IdTecnico" name="IdTecnico" formControlName="IdTecnico"/>
    <div class="alert-danger"
      *ngIf="
        myForm.get('IdTecnico').invalid &&
        (myForm.get('IdTecnico').dirty || myForm.get('IdTecnico').touched)
      "
    >
      <div *ngIf="myForm.get('IdTecnico').errors.required">
        El IdTecnico es requerido
      </div>
      <div *ngIf="myForm.get('IdTecnico').errors.minlength">
        El IdTecnico debe ser mínimo de 4 caracteres
      </div>
      <div *ngIf="myForm.get('IdTecnico').errors.maxlength">
        El IdTecnico debe ser máximo de 30 caracteres
      </div>
    </div>
  </div>
  
  <div class="form-group">
    <label for="semanaDelAno">Semana del año (*)</label>
    <input
      type="number"
      class="form-control"
      id="semanaDelAno"
      formControlName="semanaDelAno"
    />
  </div>

  <button type="submit" class="btn btn-primary" [disabled]="myForm.invalid">Enviar</button>
</form>

表单只是几个文本框和一个按钮,其想法是,例如在第一个字符上只输入一个字符时,应该会出现最小长度错误。

【问题讨论】:

  • 看起来不错?试试 {{ myForm.get('IdTecnico').errors | json }} 在模板中的某处(ngIf 之外),看看它显示了什么?
  • 按下按钮时出现Null
  • 很奇怪。可以去掉FormControl中的默认值吗?
  • 完成...这是 form.value {IdTecnico: 1, semanaDelAno: 1} IdTecnico: 1 semanaDelAno: 1 [[Prototype]]: Object null 仍然出现
  • @JhonJairoHernandezPulgarin minLength, maxLength 不适用于 type=number 应该是 type='text' check

标签: angular validation angular-reactive-forms angular11 error-messaging


【解决方案1】:

您的要求应该可以正常工作,因为它设置正确。对于IdTecnico 输入,您设置type="number"。要验证数字类型输入,您不能使用minLengthmaxLength。您可以查看this 胎面以获取更多信息。如果您确实需要数字输入,您可以尝试使用minmax 验证器。但是,查看您的输入时,您最好使用文本输入并添加一些自定义验证器来检查输入是否为某个数值。

没有看到@JhonJairoHernandezPulgarin 的评论 - 你可以投票,因为它是正确的。

【讨论】:

    猜你喜欢
    • 2021-05-05
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2020-12-12
    • 2013-03-10
    • 2019-05-18
    相关资源
    最近更新 更多