【问题标题】:Angular input form not validating on first click (Reactive form)Angular 输入表单在第一次单击时未验证(反应式表单)
【发布时间】:2018-06-15 16:10:26
【问题描述】:

我正在制作一个需要验证每个输入字段(月、日、年)的日期选择器组件。我希望在月份值有效之前禁用我的日期和年份输入字段,并且在日期有效之前禁用我的年份输入。我的表单上有一个附加到“验证”方法的点击事件,该方法检查该值是否大于 0 或小于/等于 12(有效月份值)。当我第一次单击输入字段以将值增加到 1 时,不会调用验证函数。但是,它适用于第二次点击。

datepicker.component.ts

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";

@Component({
  selector: "app-datepicker",
  templateUrl: "./datepicker.component.html",
  styleUrls: ["./datepicker.component.css"]
})
export class DatepickerComponent implements OnInit {
  myform: FormGroup;
  dayDisabled: boolean = true;
  yearDisabled: boolean = true;

  ngOnInit() {
    this.myform = new FormGroup({
      month: new FormControl('', [Validators.required]),
      day: new FormControl({ value: '', disabled: true }, [
        Validators.required
      ]),
      year: new FormControl(
        { value: '', disabled: true },
        Validators.required
      )
    });
  }

  get month() {
    return this.myform.get("month");
  }

  get day() {
    return this.myform.get("day");
  }

  get year() {
    return this.myform.get("year");
  }

  validate() {
    if (this.month.value >= 13 || this.month.value === 0 || this.month.value === null) {
      this.myform.controls.day.disable();
    } else {
      this.myform.controls.day.enable();
    }
  }
}

datepicker.component.html

<form [formGroup]="myform" (keyup)="validate()" (click)="validate()">
  <fieldset>
    <legend>
      <span *ngIf="month.dirty && day.disabled">
        Please enter a valid month
      </span>
    </legend>
    <div>
      <div>
        <label>
          Month
        </label>
        <input
        type="number" 
        min="1" 
        max="12"
        id="month"
        formControlName="month"
        name="month">
      </div>
      <div>
        <label>
          Day
        </label>
        <input 
        type="number" 
        min="1" 
        max="31" 
        id="day"
        formControlName="day"
        name="day">
      </div>
      <div>
        <label>
          Year
        </label>
        <input 
        type="number" 
        min="1900" 
        max="2019" 
        id="year"
        formControlName="year"
        name="year">
      </div>
    </div>
  </fieldset>
</form>

【问题讨论】:

    标签: angular typescript angular-forms


    【解决方案1】:

    通过添加“输入”事件处理程序来修复它

    <form [formGroup]="myform" (input)="validate()" (keyup)="validate()" (click)="validate()">
    </form>
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2018-05-24
      • 2020-09-07
      • 1970-01-01
      相关资源
      最近更新 更多