Angular 表单不断返回 false (Angular 2)

Angular form keep returning false (Angular 2)

我在 Angular 2 中有一个表单,我正在通过模型驱动的方式对其进行验证。我想知道如何将状态从 false 更改为 true,因为我有验证规则,即使用户填写正确,它也会一直返回无效(false)。这是 HTML 代码。

<div class="wrap-page">
  <form [formGroup]="myForm" novalidate class="form-contato" (ngSubmit)="enviarMensagem(myForm.value, myForm.valid)">
    <div class=row>
      <div class="col s12">
        <h4> Contato </h4>
      </div>
      <div class="col s12 m12 l6">
        <label> Nome: </label>
        <input type="text" name="nome" formControlName="nome" class="forms-econ" required placeholder="ex: José Silva">
        <div class="div-validar">
          <span [hidden]="myForm.controls.nome.valid || (myForm.controls.nome.pristine && !submitted)">
            Nome Inválido (mínimo 3 caracteres).
          </span>
        </div>
      </div>
      <div class="col s12 l6">
        <label> E-mail: </label>
        <input type="email" class="forms-econ" formControlName="email" required name="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
          placeholder="exemplo@exemplo.com">
        <div class="div-validar">
          <span [hidden]="myForm.controls.email.valid || (myForm.controls.email.pristine && !submitted)">
            E-Mail inválido
          </span>
        </div>
      </div>


      <div class="col s12 l6">
        <label>Telefone: </label>
        <input type="tel" class="forms-econ" name="telefone" formControlName="telefone" pattern="[0-9]" placeholder="(xx)9 9999-99999">
      </div>
      <div class="col s12 l6">
        <label> Motivo do Contato: </label>
        <select name="assunto" formControlName="assunto" class="forms-econ">
          <option value="motivo_01">Motivo 01</option>
          <option value="motivo_02">Motivo 02</option>
          <option value="motivo_03">Motivo 03</option>
          <option value="motivo_03">Motivo 04</option>
        </select>

      </div>
      <div class="col s12">
        <label> Mensagem: </label>
        <textarea name="mensagem" formControlName="mensagem" placeholder="Mensagem..." rows="15"> 
        </textarea>
        <div class="div-validar">
          <span [hidden]="myForm.controls.mensagem.valid || (myForm.controls.mensagem.pristine && !submitted)">
            O campo mensagem é obrigatório
          </span>
        </div>
      </div>
       <div class="col s12">
        <label> ID: </label>
        <textarea name="id" formControlName="id" placeholder="Mensagem..." rows="15"> 
        </textarea>
      </div>
      <h1> {{myForm.valid | json}} </h1> // <-- Here is where I'm printing the status of the form (always return false)
      <div class="col s12 right-align">
        <input type="submit" value="Enviar" class="btn-form">
      </div>

    </div>
  </form>
</div>

这是组件。

import { Component, Input } from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {formContato} from './contato.interface';
import {ContatoService} from './contato.service';

@Component({
  moduleId: module.id,
  selector: 'contato',
  templateUrl: `contato.component.html`,
  providers: [ContatoService]
})
export class ContatoComponent  { 

  public contato:formContato;
  public myForm: FormGroup;
  public submitted: boolean; 
  public events: any[] = []; 

  constructor(private _fb: FormBuilder, private mensagemContato:ContatoService) { } 

    ngOnInit() {  
      this.myForm = this._fb.group({
        nome: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
        email: ['', <any>Validators.required],
        telefone: ['', <any>Validators.required],
        assunto: ['', <any>Validators.required],
        mensagem: ['', <any>Validators.required],
        id: ['']
      })      
    }


    enviarMensagem(model: formContato, isValid: boolean) {
        this.submitted = true;      
        console.log(model, isValid); // -< another way to print the status of the form (always false)
    }
}

提前致谢:)

在Angular 2 中,不需要在(ngSubmit) 上传递valid 实体,只需将所需的表单名称传递给表单组指令即可。

(ngSubmit)="enviarMensagem(myForm)"


enviarMensagem({model, valid }: {model: Object, valid: boolean}) {
    this.submitted = true;      
    console.log(model, valid); 
}

您的问题与电子邮件和 phone 验证有关。他们总是验证为 false.

由于您使用的是反应式表单,我建议您将 pattern 检查移动到表单的构建中,例如:

email: ['', [<any>Validators.required, Validators.pattern(....)]],

那么我假设您想从一开始就告知字段是必需的。这可以通过多种方式完成,这里我展示两种可能的解决方案:

<span *ngIf="myForm.get('nome').hasError('required')">
   Name required!
</span><br>

或:

<span *ngIf="!myForm.controls.nome.pristine">
   Name required!
</span><br>

并且如其他答案中所述,您无需在提交中传递 myForm.valid

我给你做了一个Plunker,我在里面设置了另一个邮箱验证:

EMAIL_REGEXP = '^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';

只是一个随机的 phone 数字验证,因为我不确定您到底需要哪种数字验证。这个检查 phone 数字是否只包含数字。

如果您愿意,您还可以在表单无效时禁用提交按钮:

<input [disabled]="!myForm.valid" type="submit" value="Enviar" class="btn-form">

但这当然取决于您! :)

希望对您有所帮助!